Python 如何将用户输入转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35582959/
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
How do I convert user input into a list?
提问by Peter Yost
I'm wondering how to take user input and make a list of every character in it.
我想知道如何获取用户输入并列出其中的每个字符。
magicInput = input('Type here: ')
And say you entered "python rocks" I want a to make it a list something like this
并假设您输入了“蟒蛇岩石”,我想将其设为类似这样的列表
magicList = [p,y,t,h,o,n, ,r,o,c,k,s]
But if I do this:
但如果我这样做:
magicInput = input('Type here: ')
magicList = [magicInput]
The magicList is just
魔术列表只是
['python rocks']
采纳答案by gtlambert
Use the built-in list()
function:
使用内置list()
函数:
magicInput = input('Type here: ')
magicList = list(magicInput)
print(magicList)
Output
输出
['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']
回答by Haris
Another simple way would be to traverse the input and construct a list taking each letter
另一种简单的方法是遍历输入并构造一个包含每个字母的列表
magicInput = input('Type here: ')
list_magicInput = []
for letter in magicInput:
list_magicInput.append(letter)
回答by Antoine
gtlamber is right. But you don't need actualy to do anyting as the string has most of the list interface (means that you can treat string as a list). You can do for instance:
gtlamber 是对的。但是您实际上不需要做任何事情,因为字符串具有大部分列表接口(意味着您可以将字符串视为列表)。例如,您可以执行以下操作:
print(magicInput[1])
print(magicInput[2:4])
Output:
输出:
'y'
'th'
回答by OupsMajDsl
or you can simply do
或者你可以简单地做
x=list(input('Thats the input: ')
and it converts the thing you typed it as a list
并将您输入的内容转换为列表
回答by Odin
a=list(input()).
It converts the input into listjust like when we want to convert the input into integer.
它将输入转换为列表,就像我们要将输入转换为integer 一样。
a=(int)(input()) #typecasts input to int