I want to strip all kinds of punctuation at the start of the string using Python. My list contains strings and some of them starting with some kind of punct
for each_string in list:
each_string.lstrip(',./";:') #you can put all kinds of characters that you want to ignore.
strip() when used without parameters strips only spaces. If you want to strip any other character, you need to pass it as a parameter to strip function. In your case you should be doing
a[i]=a[i].strip(',')
Assuming you want to remove all punctuation regardless of where it occurs in a list containing strings (which may contain multiple words), this should work:
test1 = ",,gets"
test2 = ",,gets,,"
test3 = ",,this is a sentence and it has commas, and many other punctuations!!"
test4 = [" ", "junk1", ",,gets", "simple", 90234, "234"]
test5 = "word1 word2 word3 word4 902344"
import string
remove_l = string.punctuation + " " + "1234567890"
for t in [test1, test2, test3, test4, test5]:
if isinstance(t, str):
print " ".join([x.strip(remove_l) for x in t.split()])
else:
print [x.strip(remove_l) for x in t \
if isinstance(x, str) and len(x.strip(remove_l))]
If you want to remove it only from the begining, try this:
import re
s='"gets'
re.sub(r'("|,,)(.*)',r'\2',s)
To remove punctuation, spaces, numbers from the beginning of each string in a list of strings:
import string
chars = string.punctuation + string.whitespace + string.digits
a[:] = [s.lstrip(chars) for s in a]
Note: it doesn't take into account non-ascii punctuation, whitespace, or digits.
Pass the characters you want to remove in lstrip
and rstrip
'..foo..'.lstrip('.').rstrip('.') == 'foo'