0

for the following split() function in Python:

hallway = "<--<--->->"

list_string = hallway.split()

print(list_string)

The output that I am getting is ["<--<--->->"] but my desired output is ["<","-","-","<","-","-","-",">","-",">"]

Can someone please explain why my code is not producing the desired output? And how can I product the desired output simply using split() ?

2
  • Please only ask one question per SO question; I edited out the 2nd question. Instead, create a 2nd SO question for any other questions. Commented Mar 27, 2021 at 0:17
  • split splits a string based on a delimiter string. By default the delimiter string it uses is a space. Since there are no spaces in your string, no delimters of any kind really, split is stymied. "List-ifying" your string as Andrej shows in his answer is the right way to go in this case. Commented Mar 27, 2021 at 0:31

3 Answers 3

2

You're getting this result because you're splitting a string and the split() method will split a list into separate chars.

Try this:

hallway = "<--<--->->"
hallwayLIST = list(hallway)

print(listway)

OR:

Create the "hallway" variable as a list to begin with...

hallway = ['<','-','-','<','-','-','-','>','-','>']

The second way takes a lot longer to type and isn't as pretty. Also, I just saw that Andrej had the same idea for converting the str into a list and saving it as a separate var.

Sign up to request clarification or add additional context in comments.

Comments

0

You can call list() on your string:

hallway = "<--<--->->"

list_string = list(hallway)
print(list_string)

Prints:

['<', '-', '-', '<', '-', '-', '-', '>', '-', '>']

Comments

0

you will get the same string, because split() method splits a string into a list by a separator given to it as first paramter and since you don't specify the seperator, the default separator is any whitespace. and your string don't have whitespace so it return the string as it is. so to get the desired output, try to convert it to a list like the answer of Andrej Kesely

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.