How to go about inputing str into tuples?

Viewed 66

Hello I'm very new to Python and having some issues with understanding tuples. This code below gets this error: "TypeError: can only concatenate tuple (not "str") to tuple"

Any idea the best way to do this? The code is supposed to take out only strings from the tuple "t" and then put them in a new tuple together.

Cheers!

    t = 1, 43.2, 'this is a string', 'what?','hello'
    t_new = tuple()

    for item in t:
         if isinstance(item, str):
              new_tuple_item = item
              t_new = t_new + new_tuple_item

    print('The filtered tuple is', t_new)
2 Answers

As stated in python docs,

Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).

To fix this, you can use

t_new = t_new + (new_tuple_item,)

This creates a new tuple that you can add to t_new

A shorter code:

t = 1, 43.2, 'this is a string', 'what?','hello'

t_new = tuple([item for item in t if isinstance(item, str)])

print('The filtered tuple is', t_new)

Output:

The filtered tuple is ('this is a string', 'what?', 'hello')

Related