Python常用模块:字符串操作

https://www.runoob.com/python3/python3-string.html

foobar = "hello world\thello!"
将字符串的第一个字符转换为大写. Hello world
print(foobar.capitalize())

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。 ----hello world-----
print(foobar.center(20, "-"))

# 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数. 2


print(foobar.count("hello"))

en = foobar.encode("UTF-8")
print(bytes.decode(en))

print(foobar.endswith("!"))
print(foobar.startswith("!"))
print(foobar.expandtabs())

print(foobar.find("world"))
print(foobar.index("world"))
print(foobar.isalpha())
print(foobar.isdigit())
print("Hello".islower())
print("123".isnumeric())
print(" ".isspace())
print("Hello".isupper())
print(",".join(("a", "b", "c")))
print(len("abc"))
print("abc".ljust(10, "*"))
print("abc".rjust(10, "*"))
print("aBc".lower())
print("AbC".upper())
print("AbCd".swapcase())
print("     abc".lstrip())
print("abc  ".rsplit())
print(max("abc"))
print(min("abc"))
print("abc".replace("a", "A"))
print("abc".rfind("c"))
print("a,b,c".split(","))
print("a\nb\n".splitlines())
print(" a b c ".strip())
print("123".zfill(10))
print("hello world".title())
print("66".isdecimal())

如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes, 通过encode()方法将字符串转为字节。Python对bytes类型的数据用带b前缀的单引号或双引号表示。x = b"Hello"

反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法;

在操作字符串时,我们经常遇到str和bytes的互相转换。为了避免乱码问题,应当始终坚持使用UTF-8编码对str和bytes进行转换。

str -> bytes
# b'Hello'
"Hello".encode('utf-8')

bytes -> str
b'Hello'.decode('utf-8')
'Hello'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风流 少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值