Python - replacing lower case letters

别等时光非礼了梦想. 提交于 2019-12-02 02:24:01

问题


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


回答1:


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.




回答2:


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'



回答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



回答4:


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)



回答5:


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


来源:https://stackoverflow.com/questions/7945487/python-replacing-lower-case-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!