2
>>> 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?

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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' 

2 Comments

Idiomatically it would be just ''.join('.' if chr.islower() else chr for chr in input).
@agf: yes, but i always felt ''.join(...) reads backward. so i do always use str.join('', ...).
3

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 

Comments

2

You are trying to replace the string "abc...xyz" instead of replacing every lowercase letter. You can achieve the wanted result by several ways:

Regular expressions

from re import sub sub("[a-z]", '.', "hello.") 

Char by char

"".join('.' if l.islower() else l for l in word) 

Comments

1

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 '......' 

1 Comment

He specifically says lowercase letters, so \w doesn't fit the bill.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.