String to list conversion, indexing?

4277 views python
-4

I have this problem where I should convert a string to a list and then take values/variables from that list.

My problem is this:

For example I have a string:

house = "Wall,floor,roof,door"

I can make this into a list with the str.split method

["Wall", "floor", "roof", "door"]

and now I wanted to take the "Wall" value out. But if I type house[0] I get 'W'. How can I make it so that the indexes point to a whole "word" in the list?

All help appreciated, thank you.

answered question

You can index a list in similar way you do with strings.

What is the problem? If house = "Wall,floor,roof,door".split(",") then house[n] will indeed return the word at the nth index...

3 Answers

12

I think you just forgot to reassign the name house to the result of str.split, still indexing into your original string house.

>>> house = "Wall,floor,roof,door"
>>> house = house.split(',')
>>> house[0]
>>> 'Wall'
>>> house[1]
>>> 'floor'

str.split does not mutate the string it is being used on, it makes a new list which gets lost unless you assign a name to it.

posted this
5

house = "Wall,floor,roof,door"
house = house.split(',')
print(house[0])

Output:

Wall

If you just tried house.split(',') and not house = house.split(','), the resulting list would not be assigned to house and house would remain a string. In that case house[0] would be the first character of the string, which is W as you mentioned.

posted this
0

if you are Just playing around to text and want to see how to get instant First word of the comma separated string then do simple:

>>> house = "Wall,floor,roof,door"
>>> house.split(",")[0]
'Wall'

OR

This is Index based approach and you can fetch any desired index 0 to 3 as First Index starts at zero :)

>>> house.split(",")[0]
'Wall'
>>> house.split(",")[1]
'floor'
>>> house.split(",")[2]
'roof'
>>> house.split(",")[3]
'door'

posted this

Have an answer?

JD

Please login first before posting an answer.