Reputation: 115
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.
Upvotes: 2
Views: 80
Reputation: 81
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!
Upvotes: 3
Reputation: 6263
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.
Upvotes: 2
Reputation: 82785
Using map
& lambda
Ex:
a= ("App(le", "M(nago","banana")
print( tuple(map(lambda x: x.replace("(",""), a)) )
Output:
('Apple', 'Mnago', 'banana')
Upvotes: 2