简体   繁体   中英

how to replace the characters of the list in python

I want to write a code in python that will replace every every small letter character with "a" , every capital letter with "A" and every digit with 0. I write code but it caused an error of x not in list , code is below

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]
for token in tokens:
    for 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');
for t in tokens:
    print t

Using regular expressions :

from re import sub

tokens = ["apple","banana","Orange", "pineApple", "10nuts"]

for i, token in enumerate(tokens):
    token = sub(r'[A-Z]', 'A', token)
    token = sub(r'[a-z]', 'a', token)
    token = sub(r'\d', '0', token)
    tokens[i] = token

print tokens
## Output: ['aaaaa', 'aaaaaa', 'Aaaaaa', 'aaaaAaaaa', '00aaaa']

You should use regular expressions to perform this 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]")

for 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 and number are precompiled regular expressions, since you are using them in a loop, this is faster.

You could also shorten down the loop to one three lines:

for token in tokens:
    token = re.sub(upper,'A',re.sub(lower,'a',re.sub(number,'0',token)))
    print token

Hope this helps

EDIT: Took my code from above, with the one-liner, but used the enumeration loop as suggested by 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]")

for i, token in enumerate(tokens):
    tokens[i] = re.sub(upper,'A',re.sub(lower,'a',re.sub(number,'0',token)))

print tokens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM