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