Question

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?

Was it helpful?

Solution 3

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]

OTHER TIPS

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]

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

>>> [x.strip('# ') for x in a]
['abc', 'def', 'ghi', 'jkl']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top