从列表项连接python字符串

2024-10-01 15:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串列表,我想把它塞进一个由下划线分隔的字符串中。我知道我可以使用循环来实现这一点,但是python做了很多没有循环的事情。python中是否已经有了这种功能?例如,我有:

string_list = ['Hello', 'there', 'how', 'are', 'you?']

我想做一个字符串,比如:

'Hello_there_how_are_you?'

我试过的:

mystr = ''    
mystr.join(string_list+'_')

但这给出了一个“TypeError:只能将list(而不是“str”)连接到list”。我知道这很简单,但不是很明显。


Tags: 字符串功能youhello列表string事情are
2条回答

明白了,我用过:

mystr+'_'.join(string_list)
'Hello_there_how_are_you?'

我想从字符串而不是列表中使用join函数。现在看来很明显了。

您可以使用连接字符来连接列表:

string_list = ['Hello', 'there', 'how', 'are', 'you?']
'_'.join(string_list)

演示:

>>> string_list = ['Hello', 'there', 'how', 'are', 'you?']
>>> '_'.join(string_list)
'Hello_there_how_are_you?'

相关问题 更多 >

    热门问题