james_kansas
james_kansas

Reputation: 165

Python - replacing lower case letters

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

Upvotes: 2

Views: 9249

Answers (5)

gecco
gecco

Reputation: 18830

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)

Upvotes: 2

Adrien Plisson
Adrien Plisson

Reputation: 23291

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'

Upvotes: 4

doug
doug

Reputation: 70028

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

Upvotes: 1

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 66920

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

Upvotes: 3

agf
agf

Reputation: 176730

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.

Upvotes: 5

Related Questions