天天看點

python中字元串函數的用法_Python内置字元串函數的用法

print('lmy name is lizhenlei'.capitalize()) #首字母大寫

print('Lmy Name is LIZHENLEI123#'.casefold()) #全變成小寫

print('Lmy Name is LIZHENLEI123#'.center(50, '-')) #一共有50個字元,把字元串放到中間

print('Lmy Name is LIZHENLEI123#'.count('L')) #查詢一共有多少個L

print('你好'.encode('utf-8')) #轉換編碼方式

print('Lmy Name is LIZHENLEI123#'.endswith('#')) #判斷結尾是不是指定字元

print('Lmy Name is \tLIZHENLEI123#'.expandtabs(50)) #設定字元串中一個Tab的長度

print('me{} is{} 3#{}'.format('aaaa', 'bbbb', 'cccc')) #格式化字元串

print('Lmy Name is LIZHENLEI123#'.find('m')) #從左向右找到想要查找的内容,并且傳回查找的第一個字母的下标

people = {'name':'lizhenlei', 'age':23}

print('My name is {name}, I {age}'.format_map(people)) #格式化字元串輸出

print('Lmy Name is LIZHENLEI123#'.isdigit())

print('123'.isdigit()) #是否為數字

print('123abcBAC'.isalnum()) #是否為字母和數字

print('123abcBAC'.isalpha()) #不知道啥意思

print('123abcBAC'.isdecimal()) #不知啥意思

print('123abcBAC'.isidentifier()) #判斷字元串是不是一個合法的變量名

print('123abc'.islower()) #判斷字元串中字母是不是都是小寫

print('123abc'.isnumeric()) #不知道啥意思

print('dobi123\n'.isprintable()) #判斷字元串是否為可列印的,或者字元串為空

print(' '.isspace()) #判斷字元串是否為空格

print('My Name Is Lizhenlei'.istitle()) #判斷字元串中的字元是否是首字母大寫,其會忽視非字母字元。

print('ABC'.isupper()) #判斷字元串中是否都為大寫字母

print('ABC'.index('A')) #與 find() rfind() 類似,不同的是如果找不到,就會引發 ValueError。

print('-'.join(['2012', '3', '12'])) #用指定的字元串,連接配接元素為字元串的可疊代對象。

print('ABC'.ljust(10,'a')) #傳回指定長度的字元串,字元串内容居左(右)如果長度小于字元串

# 長度,則傳回原始字元串,預設填充為 ASCII 空格,可指定填充的字元串。

print('ABC123#'.lower()) #将字元串中的大寫字母變成小寫字母

print('\n ABC123# \n'.lstrip()) #去掉左邊的空格和回車

a = 'dobi is a dog'

table = str.maketrans('dobi', 'alph')

print(a.translate(table)) #maktrans 是一個靜态方法,用于生成一個對照表,以供 translate 使用。

#如果 maktrans 僅一個參數,則該參數必須是一個字典,字典的 key 要麼是一個 Unicode 編碼(一個整數),

# 要麼是一個長度為 1 的字元串,字典的 value 則可以是任意字元串、None或者 Unicode 編碼。

print('ABC123#'.partition('A')) #按字元串的内容切割字元串

print('dog wow wow jiao'.replace('wow', 'wang')) #按規則替換字元串的内容

print('ABC123#A'.rfind("A")) #從右向左找字母

print('ABC123#A'.rindex('A')) #從右向左找字母 如果找不到,就會引發 ValueError。

print('ABC123#A'.rjust(50, 'a')) #在字元串左邊補空格

print('ABC123#A'.rpartition('A')) #按規則切割字元串

print('ABC123#A'.rsplit()) #不太清楚

print('ABC123#A'.rstrip()) #不太清楚

print('ABC123#A'.split())

print('ABC123#A'.splitlines())

print('ABC123#A'.startswith())

print('ABC123#A'.strip())

print('ABC123#A'.swapcase())

print('ABC123#A'.translate())

print('ABC123#'.title()) #将字元串中每個“單詞”首字母大寫。其判斷“單詞”的依據則是

# 基于空格和标點,是以應對英文撇好所有格或一些英文大寫的簡寫時,會出錯。

print('abc123#'.upper()) #将字元串中的小寫字母變成大寫字母

print('abc123#'.zfill(10)) #用 '0' 填充字元串,并傳回指定寬度的字元串。