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

Python中使用的10个字符串函数

发布时间:2023-06-20 17:42:36

Python中的字符串是由单引号或双引号括起来的一组字符,是一种基本的数据类型。在Python中,字符串是不可变序列,因此在对字符串进行操作时,需要使用字符串相关的函数。下面介绍Python中使用的十个字符串函数。

1. len()函数

len()函数用于返回字符串的长度,语法为:len(string),其中string表示要计算长度的字符串。例如:

s = 'hello world'
print(len(s))

输出结果为:11

2. upper()函数

upper()函数用于将字符串中的字母全部转换成大写字母,语法为:string.upper(),其中string表示要进行转换的字符串。例如:

s = 'hello world'
print(s.upper())

输出结果为:HELLO WORLD

3. lower()函数

lower()函数用于将字符串中的字母全部转换成小写字母,语法为:string.lower(),其中string表示要进行转换的字符串。例如:

s = 'HELLO WORLD'
print(s.lower())

输出结果为:hello world

4. strip()函数

strip()函数用于去除字符串首尾的空格或指定的字符,语法为:string.strip([chars]),其中chars表示要去除的指定字符,如果不指定,则默认去除空格。例如:

s = ' hello world '
print(s.strip())

输出结果为:hello world

5. split()函数

split()函数用于将字符串按照指定的分隔符分割成一个列表,语法为:string.split(sep=None, maxsplit=-1),其中sep表示分隔符,maxsplit表示最大分割次数。例如:

s = 'hello,world'
print(s.split(','))

输出结果为:['hello', 'world']

6. join()函数

join()函数用于将一个序列中的元素按照指定的分隔符连接成一个字符串,语法为:sep.join(seq),其中sep表示分隔符,seq表示要连接的序列。例如:

l = ['hello', 'world']
print(','.join(l))

输出结果为:hello,world

7. replace()函数

replace()函数用于将字符串中的指定子串替换成另一个指定子串,语法为:string.replace(old, new, count=-1),其中old表示要替换的子串,new表示替换后的子串,count表示最大替换次数。例如:

s = 'hello world'
print(s.replace('world', 'python'))

输出结果为:hello python

8. find()函数

find()函数用于查找字符串中是否包含指定的子串,如果包含则返回子串的下标,如果不包含则返回-1,语法为:string.find(sub, start=0, end=len(string)),其中sub表示要查找的子串,start和end表示查找起始位置和结束位置。例如:

s = 'hello world'
print(s.find('world'))

输出结果为:6

9. count()函数

count()函数用于返回字符串中指定子串出现的次数,语法为:string.count(sub, start=0, end=len(string)),其中sub表示要计算出现次数的子串,start和end表示计算起始位置和结束位置。例如:

s = 'hello world'
print(s.count('l'))

输出结果为:3

10. isdigit()函数

isdigit()函数用于判断字符串是否只包含数字字符,如果是返回True,否则返回False,语法为:string.isdigit(),其中string表示要判断的字符串。例如:

s1 = '123'
s2 = '123a'
print(s1.isdigit())
print(s2.isdigit())

输出结果为:True False

这些字符串函数在Python中的使用非常广泛,可以大大简化字符串的操作过程。对于初学者来说,掌握这些函数是非常基础和必要的。