how to replace the characters of the list in python -
i want write code in python replace every every small letter character "a" , every capital letter "a" , every digit 0. write code caused error of x not in list, code below
tokens = ["apple","banana","orange", "pineapple", "10nuts"] token in tokens: ch in token: if ch.islower(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'a'); elif ch.isupper(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'a'); elif ch.isdigit(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'0'); t in tokens: print t
you should use regular expressions perform task:
import re tokens = ["apple","banana","orange", "pineapple", "10nuts"] upper = re.compile(r"[a-z]") lower = re.compile(r"[a-z]") number = re.compile(r"[0-9]") token in tokens: token = re.sub(upper,'a',token) token = re.sub(lower,'a',token) token = re.sub(number,'0',token) print token
the variables upper, lower , number precompiled regular expressions, since using them in loop, faster.
you shorten down loop 1 3 lines:
for token in tokens: token = re.sub(upper,'a',re.sub(lower,'a',re.sub(number,'0',token))) print token
hope helps
edit: took code above, one-liner, used enumeration loop suggested pzp1997:
import re tokens = ["apple","banana","orange", "pineapple", "10nuts"] upper = re.compile(r"[a-z]") lower = re.compile(r"[a-z]") number = re.compile(r"[0-9]") i, token in enumerate(tokens): tokens[i] = re.sub(upper,'a',re.sub(lower,'a',re.sub(number,'0',token))) print tokens
Comments
Post a Comment