Python-替换小写字母
>>> import string
>>> word = "hello."
>>> word2 = word.replace(string.lowercase, '.')
>>> print word2
hello.
我只是希望所有小写字母都变成句号。
我在这里做错了什么?
>>> 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用正则表达式:
str.replace
正在查找字符串abcdefghijklmnopqrstuvwxyz
来替换它与.
,而不是寻找每个单独的字母来替换。Use a regular expression:
str.replace
is looking for the stringabcdefghijklmnopqrstuvwxyz
to replace it with.
, not looking for each individual letter to replace.你应该使用
string.translate()
:string.maketrans()
函数是一个函数,有助于构建适合的映射string.translate()
函数。或者,您可以使用生成器简单地迭代字符串:
you should use
string.translate()
:the
string.maketrans()
function is a function which helps building a mapping suitable for thestring.translate()
function.alternatively, you can simply iterate through the string, using a generator:
string.lowercase
是'abcdefghijklmnopqrstuvwxyz'
。您的代码将用句号替换整个 26 个字母字符串的每一次出现。相反,您想使用
re
模块的子
函数: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'ssub
function:您正在尝试替换字符串“abc...xyz”,而不是替换每个小写字母。
您可以通过多种方式获得想要的结果:
正则表达式
逐个字符
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
Char by char
我认为您不能使用 r*eplace* 进行这样的映射,但您可以使用简单的正则表达式执行您想要的操作:
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: