欢迎访问宙启技术站
智能推送

Python字符串函数:查找和替换

发布时间:2023-07-04 10:08:21

Python字符串函数中有很多用于查找和替换的函数,以下是其中一些常用的函数:

1. find():用于查找子字符串在字符串中的位置。如果找到了子字符串,则返回子字符串在字符串中的起始位置;如果没有找到,则返回-1。

示例:

   str1 = "hello world"
   index = str1.find("world")
   print(index)  # 输出 6
   

2. replace():用新的字符串替换原字符串中的子字符串,并返回替换后的字符串。如果没有找到子字符串,则不进行替换。

示例:

   str1 = "hello world"
   new_str = str1.replace("world", "python")
   print(new_str)  # 输出 hello python
   

3. count():返回子字符串在字符串中出现的次数。

示例:

   str1 = "hello world"
   count = str1.count("o")
   print(count)  # 输出 2
   

4. startswith():判断字符串是否以指定的子字符串开头,并返回布尔值。

示例:

   str1 = "hello world"
   is_startswith = str1.startswith("hello")
   print(is_startswith)  # 输出 True
   

5. endswith():判断字符串是否以指定的子字符串结尾,并返回布尔值。

示例:

   str1 = "hello world"
   is_endswith = str1.endswith("world")
   print(is_endswith)  # 输出 True
   

6. split():将字符串按照指定的分隔符分割成多个子字符串,并返回一个列表。

示例:

   str1 = "hello,world"
   str_list = str1.split(",")
   print(str_list)  # 输出 ['hello', 'world']
   

7. join():将列表中的多个字符串按照指定的分隔符合并成一个字符串。

示例:

   str_list = ['hello', 'world']
   new_str = ",".join(str_list)
   print(new_str)  # 输出 hello,world
   

8. strip():去除字符串两端的空格或指定的字符,默认去除空格。

示例:

   str1 = "   hello world   "
   new_str = str1.strip()
   print(new_str)  # 输出 hello world
   

这些函数在字符串处理中非常常见和有用。通过使用这些函数,可以方便地查找和替换字符串中的内容。