Safiya Hamid
Safiya Hamid

Reputation: 53

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? Output for the statement print(b[0]) is:

abc

What I want is:

a

Thanks in advance!

Upvotes: 1

Views: 1152

Answers (3)

tamahom
tamahom

Reputation: 162

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.

Upvotes: 1

Kevin Mayo
Kevin Mayo

Reputation: 1159

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

Upvotes: 2

bigbounty
bigbounty

Reputation: 17408

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']

Upvotes: 0

Related Questions