2010年12月7日 星期二

[Python] String 字串 速記

>>> s = 'Hank'
>>> len(s)  # 字串長度
4

>>> s[0]
'H'

>>> s[1]
'a'

>>> s[-1]
'k'

>>> s
'Hank'

>>> s[1:3]
'an'



>>> s[:3]
'Han'

>>> s[:-1]
'Han'

>>> s + ' Wang'
'Hank Wang'

>>> s
'Hank'

>>> s*5
'HankHankHankHankHank'

>>> s[0] = 'z' # 不得指定變更字串
TypeError: 'str' object does not support item assignment

>>> s = 'z' + s[1:] # 產生新物件
>>> s
'zank'

>>> s.find('an')
1

>>> s.replace('an', 'zz')
'zzzk'

 >>> line = 'a,b,c,d'
>>> line.split(',')
['a', 'b', 'c', 'd']

>>> s.upper()
'ZANK'

>>> s.isalpha()
True

>>> s.isdigit()
False

>>> a = '2'
>>> a.isdigit()
True

>>> s = 'aaa,bbb   '
>>> s.rstrip()  # 移除右側空白字元
'aaa,bbb'


查看某函式的用途:
>>> help(s.strip)
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> string or unicode
  
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping



>>> msg = """ aaabbbccc'''""
abcdeff"""
>>> msg
' aaabbbccc\'\'\'""\nabcdeff'


Reference:
string — Common string operations
Learning Python, 3e
Related Posts Plugin for WordPress, Blogger...