四、string操作

  • 连接字符串
s1 = "hello"
s2 = " world"
s = s1 + s2
print(s)

#中间插入一个元素
string = "1234567"

newstr = string[:3] + "a" + string[3:]
print(newstr)

显示结果
123a4567
  • 截取字符串
string = "hello world"
print(string)
sub = string[0:3]
print(sub)
  • 替换字符
string = "hello world"
s = string.replace("e", "a")
print(s)
print(string)
  • 包含 查找
s1 = "abcdef"
s2 = "bcd"

print(s2 in s1)
print(s1.find(s2))
  • 大写、小写
string = "Hello World"
# 小写
print(string.lower())
# 大写
print(string.upper())
# 开头字母大写
print(string.capitalize())
print(string)
  • 以...开头
s1 = "abcdef"
isstart = s1.startswith("abc")
print(isstart)
isend = s1.endswith("ef")
print(isend)
  • 编码转换
# 网页读出的数据 会出现乱码 或unicode编码
s = str(html, "utf-8")
print(s)

你可能感兴趣的:(四、string操作)