首頁>技術>

python 自帶了一些 function 函式可用在 string 操作上。

大寫化 string

可以使用 upper() 函式將字串大寫化。

a = "Hello, World!"print(a.upper())PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyHELLO, WORLD!
小寫化 string

和上面相反,lower() 函式可以實現字串小寫化。

a = "Hello, World!"print(a.lower())PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyhello, world!
剔除空格

實際開發中經常會存在 string 的前後存在空格,要想移除的話可以使用 strip() 來踢掉字串前後的空格。

a = " Hello, World! "print(a.strip()) # returns "Hello, World!"PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyHello, World!
替換字串

使用 replace() 函式可以實現將 string 中某一個子串替換成另一個子串。

a = "Hello, World!"print(a.replace("H", "J"))
切分字串

使用 split() 函式將一個字串按照指定分隔符轉換成陣列,如下所示:

a = "Hello, World!"print(a.split(",")) # returns ['Hello', ' World!']PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py['Hello', ' World!']
跳脫字元

如果想在字串中插入一個非法字元,要處理這種情況需要將非法字元進行 轉義,用法就是在 非法字元 前使用 \ 即可。

先看一個錯誤的場景。

txt = "We are the so-called "Vikings" from the north."print(txt)PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py  File "e:/dream/markdown/python/app/app.py", line 2    txt = "We are the so-called "Vikings" from the north."                                       ^SyntaxError: invalid syntax

正確的做法如下:

txt = "We are the so-called \"Vikings\" from the north."print(txt)PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyWe are the so-called "Vikings" from the north.

關於更多的方法使用,可參照如下圖:

9
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 要精通SQL最佳化?首先要看懂explain關鍵字