python 自帶了一些 function 函數可用在 string 操做上。python
能夠使用 upper()
函數將字符串大寫化。git
a = "Hello, World!" print(a.upper()) PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py HELLO, WORLD!
和上面相反,lower()
函數能夠實現字符串小寫化。github
a = "Hello, World!" print(a.lower()) PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py hello, 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.py Hello, World!
使用 replace()
函數能夠實現將 string 中某一個子串替換成另外一個子串。markdown
a = "Hello, World!" print(a.replace("H", "J"))
使用 split()
函數將一個字符串按照指定分隔符轉換成數組,以下所示:app
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!']
若是想在字符串中插入一個非法字符,要處理這種狀況須要將非法字符進行 轉義
,用法就是在 非法字符 前使用 \
便可。函數
先看一個錯誤的場景。spa
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
正確的作法以下:code
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 We are the so-called "Vikings" from the north.
關於更多的方法使用,可參照以下圖:blog
譯文連接: https://www.w3schools.com/pyt...
更多高質量乾貨:參見個人 GitHub: python