简体   繁体   English

如何从字符串中删除字符?

[英]How to delete character from a string?

I'm a beginner in python and i started to learn python 3 without learning python 2. I'm trying to apply the string.translate() function which I've learnt that is not supported in python 3. 我是python的初学者,我开始学习python 3而不学习string.translate() 。我正在尝试应用我已经了解到的python 3不支持的string.translate()函数。

from string import maketrans


intab = "0123456789"
outtab = ""
trantab = maketrans(intab, outtab)
str = "p1y2t3h4o5n6"
print(str.translate(trantab))

running it gives following error: 运行它会出现以下错误:

Traceback (most recent call last):
  File "C:\Users\Nahid\Desktop\test.py", line 1, in <module>
from string import maketrans
ImportError: cannot import name 'maketrans'

I intend to get the output as python . 我打算将输出作为python How can I do that? 我怎样才能做到这一点?

请改用str.maketrans静态方法(请注意,您无需导入它)。

Answer to the question 回答问题

Don't use the name str for your string variable. 不要在字符串变量中使用名称str It will mask the built-in str : 它将掩盖内置的str

intab = "0123456789"
outtab = intab[::-1]
trantab = str.maketrans(intab, outtab)
mystring = "p1y2t3h4o5n6"
print(mystring.translate(trantab))

Output: 输出:

p8y7t6h5o4n3

Your intab and outtab must have the same length. 您的intabouttab必须具有相同的长度。 Most functions from string in Python 2 became methods of str for a while in Python 2 and were dropped as functions from string in Python 3. So use str.maketrans() . Python 2中大多数来自string函数在Python 2中都变成了str方法,并在Python 3中作为string中的函数被删除。因此请使用str.maketrans()

Solving the problem 解决问题

If want to remove characters from a string you can do: 如果要从字符串中删除字符,可以执行以下操作:

remove = set("0123456789")
mystring = "p1y2t3h4o5n6"
print(''.join(x for x in mystring if x not in remove))

Output: 输出:

python

If you want to remove numbers you can also do: 如果要删除数字,也可以执行以下操作:

print(''.join(x for x in mystring if not x.isdigit()))

Output: 输出:

python

As already mentioned in from Python 3.x you need to use the static method str.maketrans . 正如Python 3.x中已经提到的那样,您需要使用静态方法str.maketrans That being said the intab and outtab must have equal length. 就是说intabouttab必须具有相等的长度。

>>> str = "p1y2t3h4o5n6"
>>> intab = "0123456789"
>>> outtab = " "
>>> trantab = str.maketrans(intab, outtab * len(intab))
>>> print(mystring.translate(trantab).replace(" ", ""))
python

But you can also do this using regular expression 但是您也可以使用正则表达式

>>> import re
>>> re.sub(r'[0-9]', '', mystring)
'python'

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

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