3

I am trying to convert a string such as 'SUP E P I C' to a tuple containing all the non-spaced strings. For example, if the input is 'SUP E P I C', then the program should return ('S', 'U', 'P', 'E', 'P', 'I', 'C') and I am trying the obvious method of looping, and I started as follows:

for ch in john:
    if ch != ' ':
        j1 += ch
    else:
        # stuff

I'm stuck because I can add the first entry of the tuple but after that skipping the space is just escaping me. Any hints would be much appreciated!

1
  • 1
    The only problem with your code is that j1 += ch won't work if j1 is a tuple and ch is a string. gnibbler's solution is clearer and simpler, and maybe even faster, but your solution is fine, except for this one problem. Commented Nov 19, 2013 at 0:02

2 Answers 2

8

tuples are immutable, so building them up one item at a time is very inefficient. You can pass a sequence directly to tuple

>>> tuple('SUP E P I C'.replace(" ",""))
('S', 'U', 'P', 'E', 'P', 'I', 'C')

or use a generator expression (overkill for this example)

>>> tuple(x for x in 'SUP E P I C' if not x.isspace())
('S', 'U', 'P', 'E', 'P', 'I', 'C')
Sign up to request clarification or add additional context in comments.

4 Comments

Excellent, just what I was looking for; thanks a lot! I'll upvote/accept once my vote lock and accept lock get free. :)
Sorry, one more question - what if we wanted to replace more than one thing? For example, if we wanted to replace the spaces with blanks (like you did) but also new-line characters with blanks, what might we do then?
@AhaanRungta, the second version will filter any whitespace. You could also use tuple('SUP E P I C'.translate(None, ' \n'))
Great! Thanks a lot. :) Accepted. But I'll have to wait 12 more minutes to upvote.
3

The problem with your code is that you're trying to add a string to a tuple; you need to add a tuple to a tuple:

j1 = ()
for ch in john:
    if ch != ' ':
        j1 += (ch,)

With that one little fix, your original code works.

And it's equivalent to the comprehension given in gnibbler's answer:

j1 = tuple(ch for ch in john if ch != ' ')

… or, for that matter, a filtercall:

j1 = tuple(filter(lambda ch: ch != ' ', john))

Except, of course, that if that "other stuff" is anything non-trivial, you won't be able to easily convert it; you'll need to stick with your original explicit loop. And there's nothing wrong with that.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.