首页 > 解决方案 > 将两个字符串方法合二为一

问题描述

我想将两个字符串方法放在一起,以便它们可以用作更短的方法。具体来说,我正在尝试制作一种既可以使字符串小写又可以删除标点符号的方法。通常你可以这样做:

import string
s.translate(str.maketrans('', '', string.punctuation)).lower()

但我希望它看起来像:

s.removeall()

我已经尝试定义一个函数,但我不确定我将如何实际将它放在一个没有连接到任何东西的意义上,并且 python 也不会将它作为一种方法读取。

我试过这个:

import string
def removeall():
    translate(str.maketrans('', '', string.punctuation)).lower()

s.removeall()

标签: pythonpython-3.x

解决方案


You wouldn't be able to make a method of str easily, but there's nothing stopping you from writing a standalone utility function:

def removeall(s):
    return s.translate(str.maketrans('', '', string.punctuation)).lower()

You would use it as s = removeall(s). Keep in mind that strings are immutable objects. There is no such thing as an in-place operation on a string. Your original expression s.translate(str.maketrans('', '', string.punctuation)).lower() creates a new string, and therefore has no net effect if you don't save the result. The same applies for the function from.


推荐阅读