Python 中的 join() 方法是一个强大的字符串方法,用于将一个可迭代对象中的字符串元素连接起来,形成一个新的字符串。

语法:

string.join(iterable)

其中,string 为连接符,iterable 为可迭代对象,如列表、元组、字符串等。

示例:

lst = ['apple', 'banana', 'orange']
result = '-'.join(lst)
print(result) # 输出:apple-banana-orange

s = 'hello world'
result = '_'.join(s)
print(result) # 输出:h_e_l_l_o_ _w_o_r_l_d

需要注意的是,join() 方法只能用于字符串类型的可迭代对象,如果可迭代对象中包含了非字符串类型的元素,则会抛出异常。

Python join() 方法详解:字符串拼接利器

原文地址: https://www.cveoy.top/t/topic/mUMm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录