1、字符串的定义
字符串是 Python 中最常用的数据类型。我们可以通常使用引号( ' 或 " )来创建字符串,三引号也可以
s0 = "hello world"
s1 = 'hello world'
# '''''' 多用于程序开头注释文档
s2 = """hello world"""
s3 = '''hello world'''
2、字符串的遍历
1.单个字符遍历
s12 = "中华人民共和国台湾省"
for c in s12:
print(c)
结果
2.根据索引遍历
s12 = "中华人民共和国台湾省"
for i in range(len(s12)):
print(i, s12[i])
结果如下:
3、字符串的常见操作
1.将字母全转为大写
s = " abc dfs Bfe sfG"
print(s.upper())
结果如下
2.将字母全转为小写
s = " abc dfs Bfe sfG"
print(s.lower())
3.将字符串单词首字母大写
s = " abc dfs Bfe sfG"
print(s.title())
4.将字符串首字母大写
s = "abc dfs Bfe sfG"
print(s.capitalize())
5.字符查找inde()or rindex()找不到报错
s = "abc dfs Bfe sfG"
print(s.index("B"))
6.字符查找find()or rfind()找不到返回-1
s = "abc dfs Bfe sfG"
print(s.find("B"))
7.字符填充center()30字符居中
s = "abc dfs Bfe sfG"
print(s.center(30, "+"))
8.rjust()向右填充,ljust()向左填充类似center()
9、zfill()向左填充0
print("中国".zfill(20))
10.startswith()是否以字符串开始 endswith()是否以该字符结束,返回布尔值
s1 = "hello world"
print(s1.startswith("h"))
print(s1.endswith("d"))
11.split()分割字符串,默认以空格分割
s1 = "hello world"
print(s1.split())
12.大小写颠倒
print("Asdfsac".swapcase())
13.替换字符
s = "abc dfs Bfe sfG"
print(s.replace("a", "A"))