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

Python字符串函数:join()、split()、replace()、strip()、format()

发布时间:2023-06-22 09:41:12

Python 的字符串函数是非常强大的,可以处理字符串的各种操作。其中有些函数可以帮助我们简化代码,提高代码的效率。在本文中,我们将介绍五种常见的字符串函数:join()、split()、replace()、strip()、format()。

join()

join() 函数可以把序列中的元素通过指定的分隔符连接起来,成为一个字符串。具体用法为:

str = separator.join(iterable)

其中,iterable 可以是字符串、列表、元组、集合等可迭代对象。separator 表示连接的分隔符。

示例:

colors = ['red', 'green', 'blue']
result = '-'.join(colors)

print(result) # red-green-blue

在上述示例中,我们把列表 colors 中的元素通过分隔符 '-' 连接起来,成为一个字符串。

split()

split() 函数可以把一个字符串按照指定的分隔符进行分割,成为一个列表。具体用法为:

list = string.split(separator)

其中,string 表示需要分割的字符串,separator 表示分隔符。

示例:

str = 'red-green-blue'
result = str.split('-')

print(result) # ['red', 'green', 'blue']

在上述示例中,我们把字符串 str 按照分隔符 '-' 进行分割,成为了一个列表。

replace()

replace() 函数可以把一个字符串中的指定子串替换为新的字符串。具体用法为:

new_string = string.replace(old, new, count)

其中,string 表示需要替换的字符串,old 表示需要被替换的子串,new 表示替换后的新字符串,count 表示替换的次数(可选)。

示例:

str = 'I like apples, and I also like bananas'
result = str.replace('like', 'love')

print(result) # I love apples, and I also love bananas

在上述示例中,我们把字符串 str 中的所有 'like' 都替换为 'love'。

strip()

strip() 函数可以去掉一个字符串的开头和结尾的空白字符。具体用法为:

new_string = string.strip()

示例:

str = '   This is a string with spaces.    '
result = str.strip()

print(result) # This is a string with spaces.

在上述示例中,我们去掉了字符串 str 开头和结尾的空格。

format()

format() 函数可以根据指定的格式输出字符串。具体用法为:

result = 'My name is {0}, and I am {1} years old.'.format(name, age)

其中,花括号 {} 表示格式化字符,数字表示要替换的变量的顺序。

示例:

name = 'Tom'
age = 20
result = 'My name is {0}, and I am {1} years old.'.format(name, age)

print(result) # My name is Tom, and I am 20 years old.

在上述示例中,我们根据指定的格式,输出了一个字符串。