2

I have a tuple like this - ('app(le', 'orange', 'ban(ana') I want to remove bracket "(" from the words app(le and ban(ana. I have done it this way:

a=("App(le", "M(nago","banana")
b= list(a)
c = []
for x in b:
    x = x.replace("(","")
    c.append(x)
c=tuple(c)

This is giving me the desired output. But I want to do it without using for loop.

3 Answers 3

3

It sound like you want to use list comprehension!

Try c = tuple(x.replace('(','') for x in b)

Here's some documentation on list comprehension!

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

1 Comment

Or just tuple(x.replace('(', '') for x in b)
2

Using map & lambda

Ex:

a= ("App(le", "M(nago","banana")
print( tuple(map(lambda x: x.replace("(",""), a)) )

Output:

('Apple', 'Mnago', 'banana')

Comments

2

Not very elegant, but it works with NO looping. While Rakesh and RMonaco's answers are probably better, this eliminates all loops.

a = '/n/'.join(a).replace('(','').split('/n/')

FYI: I did a quick speed test of Rakesh, RMonaco, and my solutions. I doubt this will be an issue, but it was a point of interest for me so I will share. After ten-million iterations (that's right, 10E6) in each solution. I think at this point it comes down to personal preference...

>>> Rakesh:   0:00:09.869150
    RMonaco:  0:00:06.967905
    tnknepp:  0:00:05.097533
>>> 

So we have a maximum difference of 0.47 microseconds per iteration.

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.