no1
no1

Reputation: 727

How to strip "#" from item inside list?

My list is,

a=["# abc" ,"def","ghi" ,"jkl #"]

and i want my output be like this,

a=["abc","def","ghi","jkl"]

I tried this code,but I am not able to strip "#"

for item in a:
    if any("#" in item):
        item.strip("#")

How to strip "#" from item inside list?

Upvotes: 0

Views: 2715

Answers (3)

TerryA
TerryA

Reputation: 59984

There are a few problems with your code:

  1. Firstly, the use of any() here is not needed. You can just do if "#" in item:

  2. Instead of modifying item (which will do absolutely nothing), you'll want to append the solution to another list, like so:


new = []
for item in a:
    if "#" in item:
        new.append(item.strip("#"))

Just remember that in python, strings are immutable, so doing str.strip() won't modify the string in place.

Also, if you want to get rid of the extra whitespace, then you'll want to add an extra space in your call to strip:

new.append(item.strip("# "))

And finally, this is where list comprehensions come in handy:

[i.strip('# ') for i in a]

Upvotes: 2

falsetru
falsetru

Reputation: 369164

Use str.strip with '# ' as argument to remove surrounding # and spaces:

>>> [x.strip('# ') for x in a]
['abc', 'def', 'ghi', 'jkl']

Upvotes: 1

Tim Wakeham
Tim Wakeham

Reputation: 1039

a = [b.replace('#', '') for b in a]

or if you want the spaces to go as well

a = [b.replace('#', '').replace(' ', '') for b in a]

Upvotes: 0

Related Questions