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

常用的Python字符串处理函数介绍

发布时间:2023-05-22 13:24:44

Python是一种灵活而强大的编程语言,具有广泛的应用。在字符串处理方面,Python提供了许多函数和模块,这些函数大大简化了字符串的操作和处理。本文将介绍一些常用的Python字符串处理函数。

1. len()函数:返回字符串的长度。例如:

s = 'hello world'
print(len(s))
# 输出:11

2. strip()函数:去除字符串开头和结尾的空格或指定字符。例如:

s = '  hello world,  '
print(s.strip())        # 去除空格
print(s.strip(', '))    # 去除逗号和空格
# 输出:
# 'hello world,'
# 'hello world'

3. split()函数:将字符串按照指定分隔符拆分成一个列表。例如:

s = '1,2,3'
print(s.split(','))
# 输出:['1', '2', '3']

4. join()函数:用指定字符连接一个字符串列表。例如:

s = ['1', '2', '3']
print(','.join(s))
# 输出:'1,2,3'

5. replace()函数:将字符串中的指定字符替换成新的字符。例如:

s = 'hello world'
print(s.replace('hello', 'hi'))
# 输出:'hi world'

6. find()函数:查找指定字符在字符串中的位置,如果没有则返回-1。例如:

s = 'hello world'
print(s.find('world'))
# 输出:6

7. capitalize()函数:将字符串的首字母大写。例如:

s = 'hello world'
print(s.capitalize())
# 输出:'Hello world'

8. lower()和upper()函数:将字符串转换成全小写或全大写。例如:

s = 'Hello World'
print(s.lower())
print(s.upper())
# 输出:
# 'hello world'
# 'HELLO WORLD'

9. isdigit()和isalpha()函数:判断字符串是否只包含数字或字母。例如:

s1 = '123'
s2 = 'abc'
s3 = 'abc123'
print(s1.isdigit())
print(s2.isalpha())
print(s3.isdigit())
print(s3.isalpha())
# 输出:
# True
# True
# False
# False

10. startswith()和endswith()函数:判断字符串是否以指定字符开头或结尾。例如:

s = 'hello world'
print(s.startswith('hello'))
print(s.endswith('world'))
# 输出:
# True
# True

11. format()函数:格式化输出字符串。例如:

name = 'Tom'
age = 18
print('My name is {}, I am {} years old.'.format(name, age))
# 输出:'My name is Tom, I am 18 years old.'

以上就是常用的Python字符串处理函数的介绍。这些函数可以让字符串的操作和处理变得更加方便和高效,能够大大提高Python编程的效率。