1. 程式人生 > >python字串魔法

python字串魔法

test = 'alEx'

print(test.capitalize())  # 首字母大寫 其他都變小寫

print(test.casefold())  # 變小寫 更牛逼

print(test.lower())  # 全部變小寫

print(test.center(20, '*'))  # 設定寬度,一共20個位置,將test放中間,其他用*拼接

print(test.count('E', 1, 2))  # test中存在E的數量,從哪開始到哪結束,不填表示從頭到尾,左開右閉

print(test.endswith('x'))  # 判斷是否以x結尾

print(test.endswith('
E', 2, 4)) print(test.startswith('a')) # 以a開始 test = 'alExalEx' print(test.find('E')) # 從前往後找尋找E出現在哪個位置(首次),可以加位置,返回-1代表沒找到 print(test.index('E')) # 未找到就報錯 test = 'I am {name}' print(test.format(name='alex')) # format格式化 print(test.format_map({'name': 'alex'})) test = 'afds324353dcz3fads5sd中
' print('*******') print(test.isalnum()) # 只有數字和字母的時候返回True,漢字也可以 print(test.isalpha()) # 判斷是否只是字母 s = 'fasd\t324\twklds' print(s.expandtabs(3)) # 三個一組尋找\t 找到之後剩餘的用空格填充 test = '123' print(test.isdigit()) # 判斷是否只是數字 print(test.isdecimal()) # 是否是數字 有侷限 print(test.isnumeric()) test = '_qw12
' # 字母 數字 下劃線 print(test.isidentifier()) # 判斷是否符合識別符號 test = 'asdfh\tjfas\n' # 是否存在不可顯示的字元 print(test.isprintable()) test = ' ' print(test.isspace()) # 判斷是否是空格 test = 'hello world' print(test.title()) # 轉換成標題 print(test.istitle()) # 判斷是否是標題 test = '你是風兒我是沙' print(' '.join(test)) # 插入空格 print(test.center(20, '*')) # 設定寬度,一共20個位置,將test放中間,其他用*拼接 test = 'alexA' print(test.ljust(20, '*')) print(test.rjust(20, "*")) print(test.zfill(20)) # 前邊用0填充 print(test.lower()) # 轉化成小寫 print(test.islower()) # 判斷是否全部是小寫 print(test.upper()) # 轉化成大寫 print(test.isupper()) # 判斷是否是大寫 test = ' ale x ' print(test.lstrip()) # 去除左邊空格,換行 print(test.rstrip()) # 去除右邊空格 print(test.strip()) # 去除兩邊空格 test = 'alex' print(test.lstrip('a')) # 去除a(以a開頭) v = 'aeiuo' m = str.maketrans('aeiou', '12345') print(v.translate(m)) # 替換 test = 'alexafdsfffsiensfls' print(test.partition('s')) # 以s做分割 print(test.rpartition('s')) print(test.split('s')) # 分割 print(test.rsplit('s')) test = 'afsd\nfda' print(test.splitlines()) # 根據換行分割