简体   繁体   English

.lower()和同一行中的正则表达式?

[英].lower() and a regular expression in the same line?

I have a regular expression that eliminates all non-alpha characters 我有一个消除所有非字母字符的正则表达式

def genLetters(string):
  regex = re.compile('[^a-zA-Z]')
  newString = regex.sub("", string)  

If I want to make this string lowercase, I have to define a new string (since they are immutable) like 如果我想将此字符串设为小写,则必须定义一个新字符串(因为它们是不可变的),例如
lowerString = newString.lower()
It seems dumb to me that I would have to make a second string just to do the to lower, but if I remove the AZ from the regex, I lose any characters that are uppercase which I don't want. 对我来说似乎很愚蠢,我只是不得不做第二个字符串才能降低音量,但是如果我从正则表达式中删除AZ ,我会丢失所有不需要的大写字符。 I just want a final product of everything lower case. 我只想要所有小写字母的最终产品。

Can this be done without the lowerString , or even cooler, can it be done in one line? 可以在没有lowerString甚至更低的情况下完成此操作,可以在一行中完成吗?

newString = regex.sub("", string).lower()

Try to think of "functions returning" as "replacing the function call with the return value of the function". 尝试将“函数返回”视为“用函数的返回值替换函数调用”。 For example in the above case, regex.sub is evaluated first, and you should imagine that that call is replaced by the return value: 例如,在上述情况下, regex.subregex.sub求值,并且您应该想象该调用将被返回值替换:

newString = "some String after substitution".lower()

This means that you can do everything you can do to a string on the return value of regex.sub . 这意味着您可以对regex.sub返回值上的字符串执行所有regex.sub You can also call methods on the return value of lower() . 您还可以在lower()的返回值上调用方法。

This also means that you can do your whole function in one line! 这也意味着您可以一次完成全部功能!

newString = re.compile('[^a-zA-Z]').sub("", string).lower()

Although this might be less readable. 尽管这可能不太可读。

By the way, the standard naming convention in python is not camel case but with underscores, so newString should be new_string . 顺便说一句,在Python标准命名约定是不是骆驼,但用下划线,所以newStringnew_string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM