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.

对于更多的办法应用,可参照如下图:

译文链接:https://www.w3schools.com/pyt...

更多高质量干货:参见我的 GitHub: python