当我尝试导入这行代码时,我收到语法错误(第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)
答案 0 :(得分:0)
我假设您要做的是反转传入的字符串,并替换" p"用" q"反之亦然,与#34; 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"
答案 1 :(得分:0)
如果你想让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
我首先镜像字符串,然后选择字符串中不存在的字符作为时间占位符,然后迭代交换对,并用占位符替换字符串中的第一个字母,第二个是第二个,占位符是第二个。