Python String Method

1 common method

s爲字符串
s.isalnum() 所有字符都是數字或者字母
s.isalpha() 所有字符都是字母
s.isdigit() 所有字符都是數字
s.islower() 所有字符都是小寫
s.isupper() 所有字符都是大寫
s.istitle() 所有單詞都是首字母大寫,像標題
s.isspace() 所有字符都是空白字符、 、、

s.isprintble() 可打印

>>> s = 'this is a string'
>>> s.capitalize()   #大寫
'This is a string'
>>> s.upper()
'THIS IS A STRING'
>>> s.lower()
'this is a string'
>>> 'This Is A String'.swapcase()  #大小寫互換
'tHIS iS a sTRING'
>>> s.find('is')



2 format method


>>> a,b = 5,42
>>> 'this is %d and that is %d'%(a,b)       #python 2

>>>'this is {0} and that is {1}'.format(a,b) #python3


>>> 'this is {0} and that is {1},this too is {1}'.format(a,b)


>>> 'this is {} and that is {}'.format(a,b) 


>>> 'this is {bob} and that is {fred}'.format(bob=a,fred=b)


>>> d=dict(bob=a,fred=b)
>>> 'this is {bob} and that is {fred}'.format(**d)



3 split  and join method


>>> s = 'This is a string of words'
>>> s.split()
['This', 'is', 'a', 'string', 'of', 'words']


>>> s.split('i')
['Th', 's ', 's a str', 'ng of words']


>>> words = s.split()

>>> for w in words:print(w)
... 
This
is
a
string
of
words


>>> new = ':' .join(words)
>>> new
'This:is:a:string:of:words'



https://docs.python.org/3.3/library/stdtypes.html#text-sequence-type-str


關於string的官方api


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章