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'
发布了312 篇原创文章 · 获赞 943 · 访问量 135万+

猜你喜欢

转载自blog.csdn.net/vbirdbest/article/details/103466201