[英]Not able to remove characters from a string in Python
我試圖遍歷代表字母的字符串x
,同時將這些值與包含某些特定字母的列表進行比較。
如果列表和字符串x
都匹配,則應從字符串x
刪除特定字符。 這是一段非常簡單明了的代碼。 我已將.replace
方法移至T。但是,當我運行代碼時,字符串x
仍顯示為原始狀態。
這是我的工作代碼:
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
x = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(x)):
if x[i] in lettersGuessed:
x.replace(x[i],'')
print x "Available Letters"
嘗試以下
x = x.replace(x[i], '')
您沒有將更改后的值重新分配回原始字符串。
簡單的錯誤。
x = x.replace(x[i],'')
您可以使用join和生成器表達式:
print("Available Letters","".join(ch if ch not in lettersGuessed else "" for ch in x ))
使用循環,只需遍歷letterGuessed中的字符並每次更新x:
for ch in lettersGuessed:
x = x.replace(ch,'') # assign the updated string to x
print("Available Letters",x)
或遍歷x是相同的邏輯:
for ch in x:
if ch in lettersGuessed:
x = x.replace(ch,'')
字符串是不可變的,因此您無法在適當位置更改字符串。 您需要將x重新分配給使用x.replace(ch,'')
創建的新字符串
In [1]: x = 'abcdefghijklmnopqrstuvwxyz'
In [2]: id(x)
Out[2]: 139933694754864
In [3]: id(x.replace("a","foo")) # creates a new object
Out[3]: 139933684264296
In [7]: x
Out[7]: 'abcdefghijklmnopqrstuvwxyz' # no change
In [8]: id(x)
Out[8]: 139933694754864 # still the same object
您可以使用python集來實現此目的:
a = ['a','b','d']
b = "abcdefgh"
print ''.join(sorted(list(set(b) - set(a))))
輸出:
cefgh Available letters
或使用列表推導來實現此目的:
a = ['a','b','d']
b = "abcdefgh"
print ''.join([x for x in b if x not in a])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.