从列表条目连接 python 字符串 [英] Concatenate python string from list entries

查看:46
本文介绍了从列表条目连接 python 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串列表,我想将这些字符串组合成一个由下划线分隔的字符串.我知道我可以使用循环来做到这一点,但是 python 可以在没有循环的情况下做很多事情.python中是否有已经具有此功能的东西?例如我有:

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

我想制作一个字符串,如:

'Hello_there_how_are_you?'

我尝试过的:

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

但这给出了类型错误:只能将列表(不是str")连接到列表".我知道这很简单,但不是很明显.

解决方案

您使用加入字符加入列表:

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

演示:

<预><代码>>>>string_list = ['你好','那里','怎么样','是','你?']>>>'_'.join(string_list)'你好,你怎么样?'

Lets say that I have a list of strings that I would like to jam together into a single string separated by underscores. I know I can do this using a loop, but python does a lot of things without loops. Is there something in python that already has this functionality? For example I have:

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

and I want to make a single string like:

'Hello_there_how_are_you?'

What I have tried:

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

But this gives a "TypeError: can only concatenate list (not "str") to list". I know its something simple like this, but its not immediately obvious.

解决方案

You use the joining character to join the list:

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

Demo:

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

这篇关于从列表条目连接 python 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆