簡體   English   中英

如何從字符串中刪除字符?

[英]How to delete character from a string?

我是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))

運行它會出現以下錯誤:

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'

我打算將輸出作為python 我怎樣才能做到這一點?

請改用str.maketrans靜態方法(請注意,您無需導入它)。

回答問題

不要在字符串變量中使用名稱str 它將掩蓋內置的str

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

輸出:

p8y7t6h5o4n3

您的intabouttab必須具有相同的長度。 Python 2中大多數來自string函數在Python 2中都變成了str方法,並在Python 3中作為string中的函數被刪除。因此請使用str.maketrans()

解決問題

如果要從字符串中刪除字符,可以執行以下操作:

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

輸出:

python

如果要刪除數字,也可以執行以下操作:

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

輸出:

python

正如Python 3.x中已經提到的那樣,您需要使用靜態方法str.maketrans 就是說intabouttab必須具有相等的長度。

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

但是您也可以使用正則表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM