在 Python 中将列表转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44105617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:43:56  来源:igfitidea点击:

Convert a List to String in Python

python

提问by hacke john

If have string stored as list under name

如果将字符串存储为名称下的列表

>>> name
['Aaron']

Using str(name) i get

使用 str(name) 我得到

>>> str(name)
"['Aaron']"

Output Required is

所需输出为

'Aaron'

Not

不是

"['Aaron']"

Because my regular expression is not recognizing it as a string.

因为我的正则表达式没有将其识别为字符串。

回答by Moinuddin Quadri

To join list of multiple elements (strings) in the list, you may use str.joinas

加入列表中的多个元素(字符串)的列表,你可以使用str.join

>>> name = ['Aaron', 'Sheron']

#    v  to join the words in the list using space ' '
>>> ' '.join(name)
'Aaron Sheron'

However, you are having a list of just one element. In order to access the element at 0th index, you need to pass index as (PS: str.joinwill work here too, but it is not required):

但是,您只有一个元素的列表。为了访问0第 index处的元素,您需要将 index 传递为(PS:str.join在这里也可以使用,但不是必需的)

>>> name = ['Aaron']

#        v fetch `0`th element in the list
>>> name[0]
'Aaron'

Please also refer:

另请参考:

回答by Nurjan

You can also use:

您还可以使用:

''.join(name)

joinjoins all elements of the list into one string.

join将列表的所有元素连接成一个字符串。

回答by Fahadsk

Already answered in this thread

已在此线程中回答

print(''.join(name))