Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string list to a tuple in Python

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!

like image 259
Ahaan S. Rungta Avatar asked Feb 27 '26 09:02

Ahaan S. Rungta


1 Answers

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')
like image 54
John La Rooy Avatar answered Mar 01 '26 22:03

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!