简体   繁体   English

如何转换包含单个字符串且字符串中包含多个条目的列表。 Python 3

[英]How to convert list which contains a single string with multiple entries inside of string. Python 3

Let's say you have a list, which contains a single string as: 假设您有一个列表,其中包含一个字符串,如下所示:

listExample = ['cat, dog, mouse, elephant']

So printing this list return the values as a single string: 因此,打印此列表将值作为单个字符串返回:

>>>'cat, dog, mouse, elephant'

How do you get this string to the point where you can get the entries as multiple strings, such as: 如何使此字符串达到可以将条目作为多个字符串获取的地步,例如:

>>>print(anotherList)
>>>['cat', 'dog', 'mouse', 'elephant']

You are describing the basic usage of str.split : 您正在描述str.split的基本用法:

>>> listExample = ['cat, dog, mouse, elephant']
>>> listExample[0].split(', ')
['cat', 'dog', 'mouse', 'elephant']

You should use the split method. 您应该使用split方法。 So do 也是

'cat, dog, mouse, elephant'.split(', ')

this will give you 这会给你

['cat', 'dog', 'mouse', 'elephant']

The ', ' means the string should be split every time there is a comma and then a space. ', '表示字符串应在每次出现逗号和空格后分开。

The list is not needed, but if you absolutely have to use the list then do 该列表不是必需的,但是如果您绝对必须使用该列表,请执行

listExample[0].split(', ')

to get the string out of the list and then split it. 从列表中取出字符串,然后将其拆分。

For more information see this 欲了解更多信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个包含字符串和列表的单例 - Create a single which contains string and list 如何将字符串包含列表转换为python中的常规列表? - how to convert string contains list to regular list in python? 将列表中的单个字符串转换为 pandas 中同一列表中的多个字符串 - Convert a single string inside list into multiple string inside that same list in pandas 将存储在变量中的多个字符串转换为 python 中的单个列表 - Convert multiple string stored in a variable into a single list in python 如何在一个列表中转换多个字符串 python - How to convert multiple string in one list python 如何将逗号分隔的字符串转换为 Python 中的项目中包含逗号的列表? - How to convert comma separated string to list that contains comma in items in Python? 如何使用python提取字符串(包含多个定界符)中的路径 - How to extract a path with in a string (which contains multiple delimiters) using python Python返回包含哪些列表项字符串 - Python return which list items string contains Python 使用包含单个反斜杠的字符串格式化字符串 - Python Format String With a String Which Contains Single Backslash Python字符串:如何查询列表内的字典,列表内的字典 - Python string: how to query a dictionary inside a list, which are inside a dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM