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

常用字符串函数详解,让你的编程更轻松

发布时间:2023-06-26 21:48:14

在编程中,字符串是最常用的数据类型之一,因此熟练掌握字符串函数对于编写高效、精确的程序非常重要。在本文中,我们将详细介绍一些常用的字符串函数,帮助您更轻松地编写程序。

1. len(字符串长度):返回字符串的长度

len(str)

例如:

str = 'hello world!'
print(len(str))

输出:

12

2. strip(删除首位空白):返回删除字符串首位的空白字符后的字符串

str.strip([chars])

例如:

str = '    hello world!    '
print(str.strip())

输出:

'hello world!'

3. lstrip(删除左侧空白):返回删除字符串左侧的空白字符后的字符串

str.lstrip([chars])

例如:

str = '    hello world!  '
print(str.lstrip())

输出:

'hello world!  '

4. rstrip(删除右侧空白):返回删除字符串右侧的空白字符后的字符串

str.rstrip([chars])

例如:

str = '  hello world!    '
print(str.rstrip())

输出:

'  hello world!'

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

str.lower()

例如:

str = 'Hello World!'
print(str.lower())

输出:

'hello world!'

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

str.upper()

例如:

str = 'Hello World!'
print(str.upper())

输出:

'HELLO WORLD!'

7. capitalize(首字母大写):将字符串的第一个字符转换为大写字母,其余字符转换为小写字母

str.capitalize()

例如:

str = 'hello world!'
print(str.capitalize())

输出:

'Hello world!'

8. title(每个单词首字母大写):将字符串中每个单词的第一个字符转换为大写字母,其余字符转换为小写字母

str.title()

例如:

str = 'hello world!'
print(str.title())

输出:

'Hello World!'

9. count(计算指定子串出现的次数):返回子串在字符串中出现的次数

str.count(sub, start= 0,end=len(string))

例如:

str = 'hello world!'
print(str.count('l'))

输出:

3

10. find(查找子串):检查字符串中是否包含子串,如果包含则返回子串的开始索引值,否则返回-1

str.find(sub, start= 0,end=len(string))

例如:

str = 'hello world!'
print(str.find('world'))

输出:

6

11. replace(替换子串):返回将字符串中所有的old子串替换为new后的字符串

str.replace(old, new[, max])

例如:

str = 'hello world!'
print(str.replace('world', 'python'))

输出:

'hello python!'

12. split(分割字符串):根据指定分隔符将字符串分割成多个子串,返回一个包含子串的列表

str.split(str="", num=string.count(str))

例如:

str = 'hello,world!'
print(str.split(','))

输出:

['hello', 'world!']

13. join(合并字符串):将字符串列表中所有的字符串合并为一个字符串,返回合并后的字符串

str.join(seq)

例如:

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

输出:

'hello,world!'

以上是一些常用的字符串函数,熟练掌握这些函数能够让您更轻松地处理和操作字符串类型的数据。在编写程序时,根据具体需求合理运用这些函数,能够让您的代码更加高效、简洁、易读。