Python 中的字符串處理詳解(原始字符串、分割、轉碼等)


字符串

Python 中沒有單獨的字符類型,字符串屬於不可變類型:

>>> str = 'abc'
>>> str[0] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

使用三引號:"""..."""'''...''',得到的字符串所見即所得

>>> "hello " "world"  # 會被自動轉換為hello world
'hello world'

分割/拼接

字符串分割函數主要有 str.split('=') 和 str.partition('='),區別在於:

  • split 輸出的是列表,partition 輸出的是元組
  • partition 的元組有三個元素,包括分割符('='),而 split 輸出只有兩個元素。
  • split 的字符參數若在字符串中不存在會報錯,而 partition 不會

將列表 / 元組中的所有元素拼接成一個字符串:

str1 = ''.join(list1)
str2 = ''.join(tuple1)

將兩個列表 / 元組中的所有元素按照下標合並:

# 例如,將列表en_sections中的字符串和zh_sections中的字符串兩兩拼接,變成一個新的列表
sections = [a + b for a, b in zip(en_sections, zh_sections)]
>>>a = [1,2,3]
>>> c = [4,5,6,7,8]
>>> list(zip(a,c))
[(1, 4), (2, 5), (3, 6)]

原始字符串

原始字符串中包括換行符之類的特殊符號

print(r'string')
print(repr(str))
>>> r'\\'
'\\\\'
>>> r'\'  # 注意不能以奇數個反斜杠結尾,這樣最后一個引號會被視作字符串的一部分
  File "<stdin>", line 1
    r'\'
       ^
SyntaxError: EOL while scanning string literal

去除空格

>>> str = ' a bc '
>>> str.strip()
'a bc'
>>> str.lstrip()
'a bc '
>>> str.rstrip()
' a bc'

編碼轉換

字符 ↔ ASCII / Unicode,使用 ord()chr() 函數

ASCII 編碼實際上是 UTF-8 編碼的一部分

UTF-8 中使用三個字節表示一個漢字

UCS2,即兩個字節表示一個字符

>>> ord('A')
65
>>> chr(97)
'a'
>>> hex(ord('龍'))
'0x9f99'
>>> chr(0x9f99)
'龍'
>>> '\u9f99'
'龍'
>>> '龍'.encode('utf-8')
b'\xe9\xbe\x99'
>>> b'\xe9\xbe\x99'.decode('utf-8')
'龍'

URL 編碼的轉換:

# Python2 的解碼方法
if sys.version_info[0] < 3:
    import urllib
    return urllib.unquote_plus(text)
    return urllib.unquote(text)
	# Python2 的編碼方法
	if isinstance(text, unicode):
        text = text.encode('utf-8', 'ignore')
    return urllib.quote_plus(text)
    return urlparse.quote(text)
# Python3 的解碼方法
import urllib.parse
return urllib.parse.unquote_plus(text)
return urllib.parse.unquote(text)
# Python3 的編碼方法
return urllib.parse.quote_plus(text)
return urllib.parse.quote(text)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM