len(str): 返回字符串的长度。
str.lower() 和 str.upper(): 将字符串转换为小写或大写。str.strip(): 去除字符串两端的空格。
str.split(sep=None): 根据指定的分隔符将字符串分割成列表。
str.join(iterable): 将可迭代对象中的字符串元素连接起来,形成一个新的字符串。
str.replace(old, new): 将字符串中的旧字符串替换为新字符串。
str.find(sub): 返回子字符串在字符串中第一次出现的位置,如果没有找到则返回-1。
str.count(sub): 返回子字符串在字符串中出现的次数。
str.startswith(prefix) 和 str.endswith(suffix): 检查字符串是否以指定的前缀或后缀开始或结束。
str.isalpha(), str.isdigit(), str.isalnum(): 检查字符串是否只包含字母、数字或字母和数字。
-----------------------------------------------------------------------------------------------------------------------
# 定义一个字符串
s = " Hello, World! "
# 计算字符串长度
print(len(s)) # 输出: 17
# 转换为小写
print(s.lower()) # 输出: " hello, world! "
# 转换为大写
print(s.upper()) # 输出: " HELLO, WORLD! "
# 去除两端空格
print(s.strip()) # 输出: "Hello, World!"
# 分割字符串
print(s.split()) # 输出: ['Hello,', 'World!']
# 连接字符串
words = ['Hello,', 'World!']
print(", ".join(words)) # 输出: "Hello, World!"
# 替换字符串
print(s.replace("World", "Python")) # 输出: " Hello, Python! "
# 查找子字符串
print(s.find("World")) # 输出: 8
# 统计子字符串出现次数
print(s.count("l")) # 输出: 3
# 检查字符串是否以指定字符串开始或结束
print(s.startswith("Hello")) # 输出: False
print(s.endswith("World!")) # 输出: False
# 检查字符串是否只包含字母、数字或字母和数字
print("hello123".isalpha()) # 输出: False
print("hello123".isdigit()) # 输出: False
print("hello123".isalnum()) # 输出: True