>>> import string >>> word = "hello." >>> word2 = word.replace(string.lowercase, '.') >>> print word2 hello. I just want all the lowercase letters to turn into full stops.
What am I doing wrong here?
Use a regular expression:
from re import sub print sub("[a-z]", '.', "hello.") str.replace is looking for the string abcdefghijklmnopqrstuvwxyz to replace it with ., not looking for each individual letter to replace.
you should use string.translate():
>>> import string >>> input = 'abcABCaAbBcC' >>> input.translate(string.maketrans(string.lowercase, '.'*26)) '...ABC.A.B.C' the string.maketrans() function is a function which helps building a mapping suitable for the string.translate() function.
alternatively, you can simply iterate through the string, using a generator:
>>> str.join('', ('.' if chr.islower() else chr for chr in input)) '...ABC.A.B.C' ''.join('.' if chr.islower() else chr for chr in input).''.join(...) reads backward. so i do always use str.join('', ...).string.lowercase is 'abcdefghijklmnopqrstuvwxyz'. Your code is replacing every occurence of that entire 26-letter string with a full stop.
Instead, you want to use the re module's sub function:
import re word = "hello." word2 = re.sub('[a-z]', '.', word) print word2 i don't think you can use r*eplace* for a mapping like that, but you can do what you want with a simple regular expression:
>>> import re >>> word = 'hello.' >>> # the pattern you want to match >>> ptn = r'[a-z]' >>> # compile the pattern >>> pat_obj = re.compile(ptn) >>> # use the "sub" method to replace text based on a pattern >>> w2 = pat_obj.sub(".", word) >>> w2 '......' \w doesn't fit the bill.