1. 程式人生 > >python基礎--字串基本操作

python基礎--字串基本操作

我簡要介紹一下python3的字串操作

如有不對,還望大家多多指教(我的部落格園:http://www.cnblogs.com/truthk/)

string = 'kzx TruthK'<br>
string.capitalize()  # 首字母大寫
string.casefold()   # 大寫全部變小寫
string.center(50, "-")  # 輸出 '---------------------kzx TruthK----------------------'
string.count('kzx')  # 統計 kzx出現次數
string.encode()  # 將字串編碼成bytes格式
string.endswith("K")  # 判斷字串是否以 K結尾
"kzx\tTruthK".expandtabs(10)  # 輸出'kzx      TruthK', 將\t轉換成多長的空格
string.find('r')  # 查詢A,找到返回其索引, 找不到返回-1
 
'9'.isdigit()  # 是否整數
string.isnumeric()
string.isprintable()
string.isspace()
string.istitle()
string.isupper()
"|".join(['kzx', 'truth', 'ke'])  # 結果 'kzx|truth|ke'
 
msg = "my name is {}, and age is {}"
print(msg.format("kzx", 'xx'))<br>結果:my name is kzx, and age is xx
mg = "my name is {name}, and age is {age}"
print(mg.format(name='TruthK', age="xx"))
結果:my name is TruthK, and age is xx
 
mg.index('n')  # 返回r所在字串的索引
 
mg.partition('is')  # 以'is'分割mg  結果('my name ', 'is', ' {name}, and age is {age}')