python 转义空格_Python 入门系列 —— 11. string 常用方法介绍

python 自带了一些 function 函数可用在 string 操作上。

大写化 string

可以使用 upper() 函数将字符串大写化。

a = "Hello, World!"
print(a.upper())


PS E:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
HELLO, WORLD!

小写化 string

和上面相反,lower() 函数可以实现字符串小写化。

a = "Hello, World!"
print(a.lower())


PS E:dreammarkdownpython> & "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:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Hello, World!

替换字符串

使用 replace() 函数可以实现将 string 中某一个子串替换成另一个子串。

a = "Hello, World!"
print(a.replace("H", "J"))

切分字符串

使用 split() 函数将一个字符串按照指定分隔符转换成数组,如下所示:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

PS E:dreammarkdownpython> & "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:dreammarkdownpython> & "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:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
We are the so-called "Vikings" from the north.

关于更多的方法使用,可参照如下图:

373e6ccb82d50429260ae12406de3492.png

0157bb1cade85d77cd65a50fe870fd66.png

ab96555f989d7cb119a91076c7b9e25d.png

译文链接:https://www.w3schools.com/python/python_strings_modify.asp

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值