简体   繁体   English

Python:将字符串转换为列表

[英]Python: convert string to list

I have the following string: 'keyword_1, keyword_2, keyword_3' 我有以下字符串:“ keyword_1,keyword_2,keyword_3”

I want to convert the string into a list with each "keyword" being an element. 我想将字符串转换为列表,每个“关键字”都是一个元素。 So it would be: [keyword_1,keyword_2,keyword_3] 它将是:[keyword_1,keyword_2,keyword_3]

How would I go about doing this? 我将如何去做呢? Thanks! 谢谢!

Use a list generator with split and trim like: 将列表生成器与splittrim一起使用,例如:

s = 'keyword_1, keyword_2, keyword_3'
[x.strip() for x in s.split(',')]

Try this: 尝试这个:

import re    
re.compile(',\s*').split('keyword_1, keyword_2, keyword_3')

split on , and zero or more space . split ,零个或多个space

try to use siplit 尝试使用siplit

Return a list of the words in the string, using sep as the delimiter string. 使用sep作为分隔符字符串,返回字符串中单词的列表。 If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). 如果指定了maxsplit,则最多完成maxsplit个分割(因此,列表最多包含maxsplit + 1个元素)。 If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). 如果未指定maxsplit,则分割数没有限制(进行所有可能的分割)。 If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). 如果给定sep,则不将连续的定界符分组在一起,而是将其视为定界空字符串(例如'1,,2'.split(',')返回['1','','2'])。 The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). sep参数可以包含多个字符(例如,'1 <> 2 <> 3'.split('<>')返回['1','2','3'])。 Splitting an empty string with a specified separator returns ['']. 使用指定的分隔符分割空字符串将返回['']。 If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. 如果未指定sep或为None,则将应用不同的拆分算法:连续的空白行将被视为单个分隔符,并且如果字符串的开头或结尾处有空格,则结果在开头或结尾将不包含空字符串。 Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. 因此,使用None分隔符拆分空字符串或仅包含空格的字符串将返回[]。

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 ']. 例如,'1 2 3'.split()返回['1','2','3'],'1 2 3'.split(None,1)返回['1','2 3' ]。

&& String to list in Python && 要在Python中列出的字符串

If you don't want to import additional modules, you could do something like this: 如果您不想导入其他模块,则可以执行以下操作:

string = 'keyword_1, keyword_2, keyword_3'
string = string.split(",")
for i in range(len(string)):
    string[i] = string[i].strip()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM