簡體   English   中英

如何轉換包含單個字符串且字符串中包含多個條目的列表。 Python 3

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

假設您有一個列表,其中包含一個字符串,如下所示:

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

因此,打印此列表將值作為單個字符串返回:

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

如何使此字符串達到可以將條目作為多個字符串獲取的地步,例如:

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

您正在描述str.split的基本用法:

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

您應該使用split方法。 也是

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

這會給你

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

', '表示字符串應在每次出現逗號和空格后分開。

該列表不是必需的,但是如果您絕對必須使用該列表,請執行

listExample[0].split(', ')

從列表中取出字符串,然后將其拆分。

欲了解更多信息,請參閱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM