简体   繁体   English

访问列表索引中字符串中的每个字符

[英]Accessing each character in a string in an index in a list

I am taking an input fro the user in a list format using:我正在使用以下列表格式从用户那里获取输入:

b=list(map(str,input().strip().split()))

If I give the input as 'abc', all of it is stored at index 0. I want each character of the string to be stored in a different index, how do I do that?如果我将输入作为“abc”,所有这些都存储在索引 0 中。我希望字符串的每个字符都存储在不同的索引中,我该怎么做? Output for the statement print(b[0]) is:语句print(b[0])的 Output 是:

abc

What I want is:我想要的是:

a

Thanks in advance!提前致谢!

An easy way is to convert it to a list directly:一种简单的方法是直接将其转换为列表:

b=list(input()) # input "abc"
print(b) # ['a', 'b', 'c']
print(b[0]) # a

you can do if you have one string:如果你有一个字符串,你可以这样做:

b = [str(i) for i in input()]

Or if you have a lot of string separated with space:或者,如果您有很多用空格分隔的字符串:

b = [str(i) for i in input().split()]

like if your input is "abc" or "abc def"就像您的输入是“abc”或“abc def”

#input "abc" b = ["a","b","c"]

#input "abc def" b = ["a","b","c","d","e","f"]

So what it does is taking every character in the string different that " " and appending it to the list and then you can access every element that you want.所以它所做的就是将字符串中的每个字符都与“”不同并将其附加到列表中,然后您就可以访问您想要的每个元素。

If you give multiple strings in one input如果您在一个输入中给出多个字符串

In [185]: b=list(map(lambda x: list(x)[0],input().strip().split()))
hi bye

In [186]: b
Out[186]: ['h', 'b']

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

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