0
点赞
收藏
分享

微信扫一扫

Python 提供了许多字符串处理方法,以下是一些常用的方法:

Python 提供了许多字符串处理方法,以下是一些常用的方法:_python

  1. capitalize():将字符串的第一个字符转换为大写字母。

pythonstring = "hello world"  
 print(string.capitalize()) # 输出: "Hello world"

  1. lower():将字符串中的所有大写字母转换为小写字母。

pythonstring = "HELLO WORLD"  
 print(string.lower()) # 输出: "hello world"

  1. upper():将字符串中的所有小写字母转换为大写字母。

pythonstring = "hello world"  
 print(string.upper()) # 输出: "HELLO WORLD"

  1. strip():删除字符串开头和结尾的空白字符(包括空格、制表符和换行符)。

pythonstring = "   hello world   "  
 print(string.strip()) # 输出: "hello world"

  1. replace():将字符串中的某个子串替换为另一个子串。

pythonstring = "hello world"  
 print(string.replace("world", "python")) # 输出: "hello python"

  1. split():将字符串按照指定的分隔符拆分成一个列表。

pythonstring = "hello,world,python"  
 print(string.split(",")) # 输出: ['hello', 'world', 'python']

  1. join():将一个列表中的元素以指定的分隔符连接成一个字符串。

pythonlist = ['hello', 'world', 'python']  
 print(",".join(list)) # 输出: "hello,world,python"

  1. find():查找子串在字符串中第一次出现的位置,如果找不到则返回-1。

pythonstring = "hello world"  
 print(string.find("world")) # 输出: 6  
 print(string.find("python")) # 输出: -1

  1. count():统计子串在字符串中出现的次数。

pythonstring = "hello world, hello python"  
 print(string.count("hello")) # 输出: 2

举报

相关推荐

0 条评论