[英]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.