教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

人工智能+Python之字符串基本操作

更新時間:2017年11月09日17時39分 來源:傳智播客 瀏覽次數:

Python字符串相關操作很多,下面我們來一一理一下,以便于更好的進行日常的操作。

1. capitalize()

將字符串的首字母轉化為大寫,其他字母全部轉化為小寫。

如: ‘hello, World’.capitalize()會輸出’Hello, world’

2. casefold()

將字符串轉化適合比較的大小寫無關的版本。

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss"。

lower(): 返回小寫字符串

upper():返回大寫字符串

3. center(width[, fillchar])

如果width小于字符串的原長度,則原樣返回。否則,

將字符串以width的長度居中,以fillchar填充,默認fillchar為空格

4. count(sub[, start[, end]])

找到start到end中的sub出現的次數

5. encode(encoding="utf-8", errors="strict")

將字符串編碼,默認為utf-8方法。errors參數會給出不同的錯誤處理模式。默認為’strict’,其他的可能值還有

‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’, 還可以是通過codecs.register_error()方法注冊的錯誤處理模式。

strict:拋出一個UnicodeError或其子類

ignore:忽略錯誤形式的數據而不拋出異常

replace: 編碼時用’?’作為替代字符,解碼時用’?’作為替代字符

xmlcharrefreplace:用xml字符引用替代

backslashreplace:用反斜線轉義序列替代

6. endswith(suffix[, start[, end]])

如果字符串以suffix結尾,則返回True,否則為False,start/end為其范圍。suffix可以是一個元祖。

7. expandtabs(tabsize=8)

8. find(sub[, start[, end]])

從start/end中找出sub最早出現的索引,如果沒找到,就返回-1 。

rfind(sub[, start[, end]])方法從右向左查找。

9. format(*args, **kwargs)

字符串格式化。可用數字索引格式,或是關鍵字參數。例如:

a = ‘{0}:{1}’.format(‘a’, ‘b’)

a = ‘{name}:{age}’.format(name=’張三’, age=’20’)

10. index(sub[, start[, end]])

和find方法類似,只是如果沒有找到,則跑出ValueError異常

rfind(sub[, start[, end]])從右往左查找。

11. isalnum()

判斷是否是字母和數字

12. isalpha()

判斷是否是字母

13. isdecimal()

14. isdigit()

判斷是否為數字

15. isidentifier()

判斷是否為Python中的標識符

16. islower()/isupper()

判斷是否為小寫/大寫

17. isnumeric()

判斷是否為

18. isprintable()

判斷是否為可打印字符串

19. isspace()

判斷是否為空格

20. istitle()

判斷是否首字母大寫,其他字母小寫

21. join(iterable)

將字符串加入到可迭代對象里面去,iterable必須是每一個元素是字符串,否則會跑出TypeError異常

a = ‘xxx’

a.join([‘aaa’, ‘bbb’, ‘ccc’])

22. ljust(width[, fillchar])

向左調整字符串,與center類似。

rjust(width[, fillchar])

向右調整字符串,與center類似。

23. strip([chars])

去除字符串中以chars中的前綴和后綴,chars默認為空格

a = ‘www.example.com’

a.strip(‘cmowz.’) à example

lstrip([chars]):去掉左邊

rstrip([chars]):去掉后邊

24. split(sep=None, maxsplit=-1)

分割字符串,指定sep為分隔符,maxsplit為最大分隔符。0表示不分割,1表示分割成2段。。。

splitlines([keepends]): keepends為True, 表示保留\n, False不保留

25. replace(old, new[, count])

替換count個old為新的new,count默認為全部

26. partition(sep)

返回分隔符前的部分,分隔符,分隔符后的部分。如果沒找到分隔符,則返回字符串本身以及兩個空字符串。

rpartition(sep):從右往左搜索

27. title()

返回首字母大寫,其他所有字母小寫的字符串

28. zfill(width)

用0填補總長度為width的字符串的左邊,如果width小于字符串的長度,則原樣返回。

29. swapcase()

轉換字符串中的每一個字母的大小寫。【注:需要更多免費學習視頻+資料+源碼,請加QQ:3276250747】

本文版權歸傳智播客人工智能+Python學院所有,歡迎轉載,轉載請注明作者出處。謝謝!
作者:傳智播客人工智能+Python學院
0 分享到:
和我們在線交談!