強烈推薦:Python字符串(string)方法整理(一)

作者:駿馬金龍
原文地址:
https://www.cnblogs.com/f-ck-need-u/p/9127699.html
python中字符串對象提供了很多方法來操作字符串,功能相當豐富。
print(dir(str))[..........'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
這些方法的使用說明見官方文檔:string methods,本文對它們進行詳細解釋,各位以后可將本文當作手冊。
這里沒有模式匹配(正則)相關的功能。python中要使用模式匹配相關的方法操作字符串,需要import re導入re模塊。關于正則模式匹配,參見:re Module Contents。
注意,python中字符串是不可變對象,所以所有修改和生成字符串的操作的實現方法都是另一個內存片段中新生成一個字符串對象。例如,'abc'.upper()將會在劃分另一個內存片段,并將返回的ABC保存在此內存中。
下文出現的"S"表示待操作的字符串。本文沒有對casefold,encode,format,format_map進行介紹,前兩者和unicode有關,后兩者內容有點太多。
1.1 lower、upper
S.lower()S.upper()
返回S字符串的小寫、大寫格式。(注意,這是新生成的字符串,在另一片內存片段中,后文將不再解釋這種行為)
例如:
>> print('ab XY'.lower())ab xy>> print('ab XY'.upper())AB XY
1.2 title、capitalize
S.title()S.capitalize()
前者返回S字符串中所有單詞首字母大寫且其他字母小寫的格式,后者返回首字母大寫、其他字母全部小寫的新字符串。
例如:
>> print('ab XY'.title())Ab Xy>> print('abc DE'.capitalize())Abc de
1.3 swapcase
S.swapcase()swapcase()對S中的所有字符串做大小寫轉換(大寫-->小寫,小寫-->大寫)。
>> print('abc XYZ'.swapcase())ABC xyz
2.1 isalpha,isdecimal,isdigit,isnumeric,isalnum
S.isdecimal()S.isdigit()S.isnumeric()S.isalpha()S.isalnum()
測試字符串S是否是數字、字母、字母或數字。對于非Unicode字符串,前3個方法是等價的。
例如:
print('34'.isdigit())Trueprint('abc'.isalpha())Trueprint('a34'.isalnum())True
2.2 islower,isupper,istitle
S.islower()S.isupper()S.istitle()
判斷是否小寫、大寫、首字母大寫。要求S中至少要包含一個字符串字符,否則直接返回False。例如不能是純數字。
注意,istitle()判斷時會對每個單詞的首字母邊界判斷。例如,word1 Word2、word1_Word2、word1()Word2中都包含兩個單詞,它們的首字母都是"w"和"W"。因此,如果用istitle()去判斷它們,將返回False,因為w是小寫。
例如:
print('a34'.islower())Trueprint('AB'.isupper())Trueprint('Aa'.isupper())Falseprint('Aa Bc'.istitle())Trueprint('Aa_Bc'.istitle())Trueprint('Aa bc'.istitle())Falseprint('Aa_bc'.istitle())False# 下面的返回False,因為非首字母C不是小寫print('Aa BC'.istitle())False
2.3 isspace,isprintable,isidentifier
S.isspace()S.isprintable()S.isidentifier()
分別判斷字符串是否是空白(空格、制表符、換行符等)字符、是否是可打印字符(例如制表符、換行符就不是可打印字符,但空格是)、是否滿足標識符定義規(guī)則。
例如:
1.判斷是否為空白。沒有任何字符是不算是空白。
print(' '.isspace())Trueprint(' \t'.isspace())Trueprint('\n'.isspace())Trueprint(''.isspace())Falseprint('Aa BC'.isspace())False
2.判斷是否是可打印字符
print('\n'.isprintable())Falseprint('\t'.isprintable())Falseprint('acd'.isprintable())Trueprint(' '.isprintable())Trueprint(''.isprintable())True
3.判斷是否滿足標識符定義規(guī)則
標識符定義規(guī)則為:只能是字母或下劃線開頭、不能包含除數字、字母和下劃線以外的任意字符。
print('abc'.isidentifier())Trueprint('2abc'.isidentifier())Falseprint('abc2'.isidentifier())Trueprint('_abc2'.isidentifier())Trueprint('_abc_2'.isidentifier())Trueprint('_Abc_2'.isidentifier())Trueprint('Abc_2'.isidentifier())True
未完待續(xù)。。。。。。
覺得不錯,點個在看唄!
