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? Output for the statement print(b[0])
is:
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"
#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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.