[英]having trouble in python with syntax for .replace
嘗試導入此代碼行時出現語法錯誤(第8行rw.replace)。 它應該工作正常嗎?
def mirror(word):
mirrorletters = str([[p,q],[q,p],[d,b][b,d]])
rw == reverse(word)
while True:
if item in word:
for mirrorletters in rw:
for p in rw:
print rw.replace('p','q')
for q in rw:
print rw.replace('q','p')
for d in rw:
print rw.replace('d','b')
for b in rw:
print rw.replace('b','d')
elif item not in word:
print(rw)
我假設您要執行的操作是反轉傳入的字符串,並用“ q”替換“ p”,反之亦然,用“ d”和“ b”替換相同的字符串?
mirrorletters = str([[p,q],[q,p],[d,b][b,d]])
引發錯誤,因為您嘗試引用p
, q
, d
和b
,都不是存在。 您需要這些字母的字符串表示形式。
rw == reverse(word)
不會將rw
設置為與==
進行比較的reverse(word)
的內容。
另外,據我所知, reverse()
不在Python 2或3的標准庫中。
您可以通過說出反向字符串
word = 'hello' r = word[::-1] print(r) # prints "olleh"
這就是我相信您正在嘗試做的事情:
def mirror(word):
# Make a list of characters to be swapped.
# "d" will be swapped with "b" and vice versa.
# The same goes for "q" and "p"
mirror_letters = [('d', 'b'), ('q', 'p')]
# Start with a new string
new_word = ''
# Go through each letter in the word and keep up with the index
for letter in word:
# Go through each "character set" in mirror_letters
for char_set in mirror_letters:
# enumerate the char_set and get an index and character of each item in the list
for index, char in enumerate(char_set):
# If the letter is equal to the character, set letter to character
if letter == char:
# Doing a little bit of "reverse indexing" here to determine which character to set letter to
letter = char_set[::-1][index]
# If we set the letter, break so we don't possibly change back.
break
# Add the letter to the new word
new_word += letter
return new_word[::-1]
輸出:
print(mirror('abcd')) # prints "bcda"
print(mirror('pqrs')) # prints "srpq"
如果要ro鏡像一個字符串然后交換一些字母,則可以使用以下函數:
def mirrorString(string, swap=[]):
mirroed = string[::-1]
i = 0
while chr(i) in mirroed:
i += 1
for a, b in swap:
mirroed = mirroed.replace(a, chr(i)).replace(b, a).replace(chr(i), b)
return mirroed
print(mirrorString("abcd", [('b', 'd'), ('p', 'q')])) # bcda
我首先鏡像字符串,然后選擇字符串中不存在的字符用作臨時占位符,然后遍歷交換對,並用占位符替換對中的第一個字母,第二個替換為占位符。第一個,占位符第二個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.