Hussein Saad
Hussein Saad

Reputation: 151

How to remove quotation from a list in python?

I have like this array in my code:

x = ['"google"','"facebook"',"youtube"]

I want the output will be like this

["google","facebook","youtube"]

how to do that?

Upvotes: 0

Views: 70

Answers (1)

aydow
aydow

Reputation: 3801

Use str.strip and a list comprehension

In [1062]: x = ['"google"','"facebook"',"youtube"]

In [1063]: [i.strip('"') for i in x]
Out[1063]: ['google', 'facebook', 'youtube']

Alternatively, you could use map instead of a list comprehension

In [1065]: list(map(lambda i: i.strip('"'), x))
Out[1065]: ['google', 'facebook', 'youtube']

You can also use str.replace

In [1074]: [i.replace('"', '') for i in x]
Out[1074]: ['google', 'facebook', 'youtube']

Comparing all three, the list comprehension with str.strip is the fastest

In [1066]: %timeit([i.strip('"') for i in x])
The slowest run took 12.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 805 ns per loop

In [1067]: %timeit(list(map(lambda i: i.strip('"'), x)))
1000000 loops, best of 3: 1.52 µs per loop

In [1075]: %timeit([i.replace('"', '') for i in x])
The slowest run took 5.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 975 ns per loop

Upvotes: 5

Related Questions