1. 程式人生 > >pytho系統學習:第二週之字串函式練習

pytho系統學習:第二週之字串函式練習

# Author : Sunny
# 雙下劃線的函式基本沒用
# 定義字串
name = 'i am sunny!'
# 首字母大寫函式:capitalize
print('-->capitalize:', name.capitalize())
# 判斷結尾函式:endswith
print('-->endswith:', name.endswith('y!'))
# 判斷開頭函式:startswith
print('-->startswith:', name.startswith('i'))
# 字元輸出居中函式:center
print('-->center:', name.center(30, '+'))

# 字元計數函式:count
print('-->count:', name.count('n'))
# tab鍵輸出轉空格函式:expandtabs //不重要
name2 = 'su\tnny!'
print('-->expandtabs:', name2.expandtabs(30))
# 字元位置判斷函式:find
print('-->find:', name.find('n')) # 返回左面第一個n的索引值
print('-->rfind:', name.rfind('n')) # 返回右面第一個n的索引值
print('-->find切片應用:', name[name.find('s'):]) # 字元find的切片應用

# 字元格式轉化(引數傳值)函式:format
name = 'sunny'
age = 23
print('-->format用法一:', '{0} is {1} years old!'.format(name, age)) # format用法一
word = '{name} is {age} years old!'
print('-->format用法二:', word.format(name='sunny', age=23)) # format用法二
print('-->format用法三:', word.format_map({'name': 'sunny', 'age': 23})) # format_map字典用法 //不常用

# 判斷字元是否是數字組成函式:isalnum
print('-->isalnum:', '123'.isalnum())
# 判斷字元是否純字母組成函式:isalpha
print('-->isalpha:', 's5'.isalpha())
# 判斷字元是否十進位制函式:isdecimal
print('-->isdecimal:', '1'.isdecimal())
# 判斷字元是否是整數:isdigit
print('-->isdigit:', '55'.isdigit())
# 判斷字元是否是純數字:isnumeric
print('-->isnumeric:', 's45'.isnumeric())
# 判斷字元是否是合法識別符號:isidentifier //不常用
print('-->isidentifier:', 'as'.isidentifier())
# 判斷字元是否都是小寫函式:islower
print('-->islower:', 'aAa'.islower())
# 字串轉化為小寫函式:lower
print('-->lower:', 'ADW'.lower())
# 判斷字元是否為空格函式:isspace
print('-->isspace:', ' '.isspace())
# 判斷字元首字母是否為大寫函式:istitle
print('-->istitle:', 'I Am'.istitle()) # 都為大寫則為true
# 將字元首字母都轉化為大寫函式:title
print('-->title:', name.title())
# 判斷字串是否為大寫函式:isupper
print('-->isupper:', name.isupper())
# 將字串轉化為大寫函式:upper
print('-->upper:', name.upper())
# 列表值關聯函式:join
print('-->join:', '+'.join(['1', '2', '3'])) # 列表值為字串
# 字串長度補齊函式:ljust/rjust
print('-->ljust:', name.ljust(30, '+'))
# 去除字串空格函式:strip/lstrip/rstrip
print('-->lstrip:', ' asad'.lstrip())
# 字元自定義加密函式:maketrans
dirc = str.maketrans('w13hc1g4', '\/[email protected]#%^&')
print('-->maketrans:', 'wghc1314'.translate(dirc))
# 字串替換函式:replace
print('-->replace:', name.replace('n', 'u'))
# 字串分割成列表函式:split
print('-->split:', '1+2+3+4'.split('+'))
# 字串大小寫互換函式:swapcase
print('-->swapcase:', name.swapcase())

字串的函式基本就這些,如果有什麼疑問,可以關注我的部落格,我們一起討論