这是给我的字符串Enter 3 random strings, separated by commas: The,Dave,Make
我希望列表只包括以下内容:["The", "Dave", "Make"]
我试过使用拆分,但它导致错误
strings = input("Enter 3 random strings, separated by commas:")
strings = strings.split()
使用string.split()
和strip()
方法:
In [2680]: s = "Enter 3 random strings, separated by commas: The,Dave,Make"
In [2686]: s.split(':')[-1].strip().split(',')
Out[2686]: ['The', 'Dave', 'Make']
试试这个:
string = 'Enter 3 random strings, separated by commas: The,Dave,Make'
lst = string.split(':')[-1].strip().split(',')
输出:
>>> lst
['The', 'Dave', 'Make']
在冒号处拆分字符串,删除多余的空格,然后在逗号处拆分。
string = 'Enter 3 random strings, separated by commas: The,Dave,Make'
result = string.split(':')[1].strip().split(',')
如果字符串是从控制台获得的,它的第一部分应该是输入提示:
strings = input("Enter 3 random strings, separated by commas:")
strings = strings.strip().split(',')
代码可以缩短为一行:
strings = input("Enter 3 random strings, separated by commas:").strip().split(',')