3

So I am trying to split a string s:

s = "l=2&w=3&h=2"

However whenever I try to use the split() function on s and store the values in list L, this comes up:

L = s.split()
L --> ['l=2&w=3&h=2']

Am I doing something wrong? How do I split this string so I get:

L = ['l','=','2','&','w','=','3','&','h','=','2']
Tahmoor Cyan
  • 129
  • 1
  • 4
  • 15

3 Answers3

5

It's actually easier than you might think.

L = list(s)

In Python, strings are iterable, just like lists. If you just need to iterate over the string, you don't even need to store it in a list.

Cody Piersall
  • 8,312
  • 2
  • 43
  • 57
5

split() with no arguments splits on whitespace, which your string contains none of. To split on every character, just convert your string directly to a list:

L = list(s)
jwodder
  • 54,758
  • 12
  • 108
  • 124
1

I don't know the whole story. I know .list() will work but I also must say this. If you import the right library, I think, you have another method:

    import re
    s = "l=2&w=3&h=2"
    print re.findall(r"[\w']+", s)
    # Prints ['1', '=', '2', '&', 'w', '=', '3', '&', 'h', '=', '2']

I got the answer from the following source. It's actually another stack exchange question:

Split Strings with Multiple Delimiters?

Not perfect, I know, but I hope it helps.

Community
  • 1
  • 1
user2932
  • 137
  • 3