簡體   English   中英

從字符串中刪除特定字符

[英]Remove specific characters from a string

我想從用戶提供的字符串中刪除所有元音。 以下是我的代碼以及我得到的輸出。 由於某些原因,for循環僅檢查第一個字符,而沒有其他檢查。

碼:

sentence = "Hello World."
sentence = sentence.lower()

for x in sentence:
    sentence = sentence.strip("aeiou")
    print (x)

print (sentence)

輸出:

hello world

我有print(x)只是為了確保它正在查看所有字符並循環顯示字符數量。 但是,當循環到達一個元音時,它似乎沒有執行我想要的操作,即從字符串中將其刪除。

如預期般運作。 strip定義為:

返回刪除前導和尾隨字符的字符串的副本。 chars參數是一個字符串,指定要刪除的字符集。

http://docs.python.org/2/library/stdtypes.html#str.strip

如此說來,它僅影響前導字符和尾隨字符-一旦找到不在剝離字符集中的字符,它就會停止查找。 無論如何,松散地說。 我沒有檢查實際實現的算法。

我認為translate是最有效的方法。 從文檔:

>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'

http://docs.python.org/2/library/stdtypes.html#str.translate

您不能從字符串中刪除字符:字符串對象是不可變的。 您所要做的就是創建一個新的字符串,其中沒有更多的沃爾夫。

x = ' Hello great world'
print x,'  id(x) == %d' % id(x)

y = x.translate(None,'aeiou') # directly from the docs
print y,'  id(y) == %d' % id(y)

z = ''.join(c for c in x if c not in 'aeiou')
print z,'  id(z) == %d' % id(z)

結果

 Hello great world   id(x) == 18709944
 Hll grt wrld   id(y) == 18735816
 Hll grt wrld   id(z) == 18735976

函數id()給定的地址差異意味着對象xyz是不同的對象,位於RAM中的不同位置

暫無
暫無

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

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