「大數據」(一百二十七)Python基礎之字符串:字符串方法

【導讀:數據是二十一世紀的石油,蘊含巨大價值,這是·情報通·大數據技術系列第[127]篇文章,歡迎閱讀收藏】

1 基本概念

python 中字符串對象提供了很多方法來操作字符串,功能相當豐富,具體有哪些方法可以通過命令 print(dir(str)) 查看,本文只對部分做介紹

「大數據」(一百二十七)Python基礎之字符串:字符串方法

<code>['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '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']/<code>

2 字符串方法介紹

2.1 大小寫轉換

<code>s.upper()  # 轉化為大寫
s.lower() # 小寫/<code>

2.2 isXXX 判斷

<code>s.isdecimal()
s.isdigit()
s.isnumeric()/<code>

測試字符串 S 是否是數字、字母、字母或數字。對於非 Unicode 字符串,前 3 個方法是等價的

<code>s.islower()
s.isupper()
s.istitle()/<code>

判斷是否小寫、大寫、首字母大寫。要求 S 中至少要包含一個字符串字符,否則直接返回 False 。例如不能是純數字。

注意, istitle() 判斷時會對每個單詞的首字母邊界判斷。例如, word1 Word2 、 word1_Word2 、 word1()Word2 中都包含兩個單詞,它們的首字母都是 "w" 和 "W" 。因此,如果用 istitle() 去判斷它們,將返回 False ,因為 w 是小寫。


分享到:


相關文章: