一、字符串的定义
在 Python 中,可以使用单引号 ' ' 、双引号 " " 或三引号 ''' ''' 、""" """ 来定义字符串。
代码示例:
s0 = "hello world"
s1 = 'hello world'
s2 = """hello world"""
s3 = '''hello world'''
print(s0, s1, s2, s3)
运行结果:
二、字符串的遍历
1.使用索引
常采用内置函数len( )。参考代码理解
代码1:
string = "我是中国人"
for i in range(len(string)):
print(string[i], end="")
结果1:
代码2:
string = "我是中国人"
for i in range(len(string)):
print(i, string[i])
通过 range(len(string)) 生成了与字符串长度相等的索引序列,然后通过索引 i 来获取字符串 string 中对应位置的字符并打印出来。
结果2:
2.for遍历
代码:
China = "我来自中华人民共和国"
for i in China:
print(i)
结果:
三、字符串的常见操作
常见操作参考代码,作用已经详细标明,可直接运行学习。
代码:
print("天生我材必有用".index("必有用")) # .index() 查找指定子字符串在原字符串中首次出现的位置
print("天生我材必有用必有用".rindex("必有用")) # .rindex() 查找子字符串在原字符串中最后一次出现的位置。
print("天生我材必有用必有用".find("必有用")) # .find() 用于在字符串中查找子字符串。如果找到了子字符串,find() 方法返回子字符串首次出现的索引位置;如果未找到,返回-1 。
print("天生我材必有用必有用".rfind("必有用")) # .rfind() 返回的子字符串在原字符串中最后一次出现的索引位置。
print("----------------------------")
print("天生我材必有用必有用".count("必有用")) # .count() 统计指定子字符串在原字符串中出现的次数。
print("----------------------------")
print("aBcD eFg".capitalize()) # 首字母大写 .capitalize()
print("aBcD eFg".upper()) # 全大写 .upper()
print("aBcD eFg".lower()) # 全小写 .lower()
print("aBcD eFg".swapcase()) # 大小写转换 .swapcase()
print("aBcD eFg".title()) # 标题 首字母大写 .title()
print("----------------------------")
print("嗨喽".center(23, " ")) # .center 用于将字符串居中,并在两侧填充指定的字符“ ”至指定的宽度。
print("嗨喽".ljust(23, "-")) # .ljust 用于将字符串左对齐,并在右侧填充指定的字符“-”至指定的宽度。
print("嗨喽".rjust(23, "+")) # .rjust 用于将字符串左对齐,并在左侧填充指定的字符“+”至指定的宽度。
print("嗨喽".zfill(23)) # .zfill 在字符串的左侧填充零,直到字符串的长度达到指定的宽度。
print("----------------------------")
print("天生我材必有用必有用".endswith("必有用")) # .endswith() 看结尾是否是括号里面的内容
print("天生我材必有用必有用".startswith("天生")) # .startswith() 看开头是否是括号里面的内容
print("----------------------------")
by_result = "天生我材必有用必有用".encode(encoding="gbk") # .encode() 将字符串编码为指定的字符编码格式。这里指定的编码格式为gbk
print(type(by_result), by_result)
str_result = by_result.decode(encoding="gbk") # .decode() 将编码后的字节数据解码为字符串。
print(type(str_result), str_result) # 解码时使用的编码格式要与编码时使用的格式一致,否则可能会导致解码错误。
print("----------------------------")
china = "中华人民共和国宪法".split("共和国") # .split() 通过指定的分隔符将字符串分割成一个列表。
print(type(china), china) # <class 'list'> ['中华人民', '宪法']
print("***".join(china)) # 中华人民***宪法
print("----------------------------")
print("中华人民共和国宪法".replace("宪法", "刑法")) # .replace() 替换指定的字符串
print("----------------------------")
print("".isalpha()) # .isalpha() 检查字符串中的所有字符是否都是字母(包括大小写)
运行结果: