Python基础教程:05字符串String的用法解析
String是 Python 中的一个内置类,表示字符串。它包含了一些用于操作字符串的方法,例如拼接、搜索、替换等。
01 查找类
#1.find():从左往右查找,用于在字符串中查找子字符串。find()方法接受两个参数,第一个参数是要查找的子字符串,第二个参数是要查找的字符串。如果子字符串存在于字符串中,则返回子字符串在字符串中的起始位置;如果子字符串不存在于字符串中,则返回-1。rfind()是从右往左查找。
# 定义一个字符串 str1 = "Hello, World!" # 定义一个子字符串 sub_str = "World" # 使用find()方法查找子字符串在字符串中的位置 start = str1.find(sub_str) # 输出结果 if start != -1: print(f"The sub-string {sub_str} is found at position {start}.") else: print(f"The sub-string {sub_str} is not found in the string.")
在上面的代码中,我们首先定义了一个字符串str1和一个子字符串sub_str。然后,我们使用find()方法在字符串str1中查找子字符串sub_str。如果找到了子字符串,则输出子字符串在字符串中的起始位置;否则,输出子字符串不在字符串中的提示信息。
#2.index():从左往右查找,方法用于获取子字符串在字符串中的位置。index()方法接受两个参数,第一个参数是要查找的子字符串,第二个参数是要查找的字符串。如果子字符串存在于字符串中,则返回子字符串在字符串中的起始位置;如果子字符串不存在于字符串中,则返回-1。index()是从右往左查找。
以下是一个示例代码,演示如何使用index()方法获取子字符串在字符串中的位置:
# 定义一个字符串 str1 = "Hello, World!" # 定义一个子字符串 sub_str = "World" # 使用index()方法获取子字符串在字符串中的位置 index = str1.index(sub_str) # 输出结果 if index != -1: print(f"The sub-string {sub_str} is found at position {index}.") else: print(f"The sub-string {sub_str} is not found in the string.")
#3.count()方法用于计算字符串中某个字符出现的次数。count()方法接受一个可迭代对象作为参数,该对象表示要计算次数的字符或子字符串。如果可迭代对象表示的是一个字符,则count()方法返回该字符出现的次数;如果可迭代对象表示的是一个子字符串,则count()方法返回子字符串中该字符出现的次数。
以下是一个示例代码,演示如何使用count()方法计算字符串中某个字符出现的次数:
# 定义一个字符串 str1 = "Hello, World!" # 定义要计算次数的字符 char = "o" # 使用count()方法计算字符出现的次数 count = str1.count(char) # 输出结果 if count != 0: print(f"The character {char} appears {count} times in the string.") else: print(f"The character {char} is not in the string.")
02 修改类
# 定义一个字符串 str1 = "Hello, World!" # 使用replace()方法替换字符串中的某个子字符串 new_str1 = str1.replace("o", "X") # 使用split()方法按照指定的分隔符将字符串分割成多个子字符串 new_str2 = str1.split("o") # 使用join()方法将多个字符串连接成一个新的字符串 new_str3 = " ".join(str1.split()) # 使用title()方法将字符串中的每个单词的首字母转换为大写 new_str4 = str1.title() # 使用lower()方法将字符串中的大写字母转换为小写字母 new_str5 = str1.lower() # 使用upper()方法将字符串中的小写字母转换为大写字母 new_str6 = str1.upper() # 使用strip()方法删除字符串两侧的空白字符 new_str7 = str1.strip() # 使用center()方法将字符串居中对齐 new_str8 = str1.center(100,'-') # 打印修改后的字符串 print(new_str1) # 输出:Hello, X! print(new_str2) # 输出:Hello, World! print(new_str3) # 输出:Hello, X! print(new_str4) # 输出:Hello, World! print(new_str5) # 输出:hello, X! print(new_str6) # 输出:hello, World! print(new_str7) # 输出:Hello, World! print(new_str8) # 输出:-------------------------------Hello, X!-------------------------------
03 删除类
string.lstrip()方法:用于删除字符串左侧的空格字符。
string.rstrip()方法:用于删除字符串右侧的空格字符。
string.strip()方法:删除字符串两侧的空白字符
04 判断类
# 判断字符串是否为空 str1 = "" if str1: print("字符串不为空") else: print("字符串为空") # 判断字符串是否为字母 str2 = "hello" if str2.isalpha(): print("字符串是字母") else: print("字符串不是字母") # 判断字符串是否为数字 str3 = "123" if str3.isdigit(): print("字符串是数字") else: print("字符串不是数字")
isspace() :用于检查字符串中是否只包含空格字符。它的参数是一个字符,可以是字母、数字或空格字符。
# 判断字符是否为空格字符 c = ' ' if c.isspace(): print(c, "是空格字符") else: print(c, "不是空格字符")
完毕!!感谢您的收看
------------往期更多精彩内容------------