python - 将两个字符串方法合二为一
问题描述
我想将两个字符串方法放在一起,以便它们可以用作更短的方法。具体来说,我正在尝试制作一种既可以使字符串小写又可以删除标点符号的方法。通常你可以这样做:
import string
s.translate(str.maketrans('', '', string.punctuation)).lower()
但我希望它看起来像:
s.removeall()
我已经尝试定义一个函数,但我不确定我将如何实际将它放在一个没有连接到任何东西的意义上,并且 python 也不会将它作为一种方法读取。
我试过这个:
import string
def removeall():
translate(str.maketrans('', '', string.punctuation)).lower()
s.removeall()
解决方案
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.
推荐阅读
- r - 在 R 中分配自定义周数
- python - 在 cmd 中安装 CX_ORACLE 时出错
- sql - 使用 WHERE 限制返回的记录?
- django - 在 Windows 上使用 Django 的 Pyinstaller - “环境只能包含字符串”
- ios - 以编程方式在 UITabBarController 和 UINavigationController 中呈现视图
- python - 有没有更好的方法来删除给定子目录中的所有 .py 和 .pyc 文件?
- google-cloud-platform - 从谷歌云中的虚拟机锁定
- javascript - JavaScript 检查值是否优越并尊重倍数
- php - 可以安全地假设 PHP 可以在次要版本之间一致地反序列化
- python - Python - 从 URL 参数读取的特殊字符