【发布时间】:2020-10-12 08:55:48
【问题描述】:
我有一个程序的代码,它将字符串中的字符替换为上标字符,每次跳转 1 个字符。
应该跳过不在我的字典中的字符,但也会影响下一个字符是否会被替换(因此,如果“not-in-dict-character”应该被替换,它会被跳过并且下一个字符不会替换,反之亦然)
应该跳过空格而不改变下一个字符。
letters = { # My dictionary for all the letters and superscript versions
'a' : 'ᵃ',
'b' : 'ᵇ',
'c' : 'ᶜ',
'd' : 'ᵈ',
'e' : 'ᵉ',
'f' : 'ᶠ',
'g' : 'ᵍ',
'h' : 'ʰ',
'i' : 'ᶦ',
'j' : 'ʲ',
'k' : 'ᵏ',
'l' : 'ˡ',
'm' : 'ᵐ',
'n' : 'ⁿ',
'o' : 'ᵒ',
'p' : 'ᵖ',
'q' : 'ᵠ',
'r' : 'ʳ',
's' : 'ˢ',
't' : 'ᵗ',
'u' : 'ᵘ',
'v' : 'ᵛ',
'w' : 'ʷ',
'x' : 'ˣ',
'y' : 'ʸ',
'z' : 'ᶻ',
'A' : 'ᴬ',
'B' : 'ᴮ',
'C' : 'ᶜ',
'D' : 'ᴰ',
'E' : 'ᴱ',
'F' : 'ᶠ',
'G' : 'ᴳ',
'H' : 'ᴴ',
'I' : 'ᴵ',
'J' : 'ᴶ',
'K' : 'ᴷ',
'L' : 'ᴸ',
'M' : 'ᴹ',
'N' : 'ᴺ',
'O' : 'ᴼ',
'P' : 'ᴾ',
'Q' : 'ᵠ',
'R' : 'ᴿ',
'S' : 'ˢ',
'T' : 'ᵀ',
'U' : 'ᵁ',
'V' : 'ⱽ',
'W' : 'ᵂ',
'X' : 'ˣ',
'Y' : 'ʸ',
'Z' : 'ᶻ'
}
x = 0
while True:
text = input('Insert text: ')
while True:
# This will ask if the user wants something like 'aᵃaᵃaᵃaᵃ' or 'ᵃaᵃaᵃaᵃa'
fos = input('Do you want the first or the second letter to be small?(f/s): ')
if fos != 'f':
if fos != 's':
print('Please insert \'f\' or \'s\' (for first and second letters).\n')
else:
break
else:
break
if fos == 'f':
x = 1
elif fos == 's':
x = 2
for e in text:
if x % 2 == 0: # If x value is even, it skips this character
x = x + 1 # Makes the x value odd, so the next character isn't skipped
continue
elif e == ' ': # Ignoring blank spaces
continue
elif e not in letters: # Ignoring characters that are not in my dict
x = x + 1
continue
elif e in letters:
text = text.replace(e, letters[e], 1) # The third parameter is
x = x + 1
print(text)
问题是,如果替换函数试图替换的字符在字符串中有重复,它不关心哪个字符是'e',而只是替换字符串中的第一个。
所以,如果用户输入 'abaaba' 和 'f',结果将是 'ᵃᵇᵃaba' 而应该是 'ᵃbᵃaᵇa'。有没有办法让替换对字符串中的哪个字符是 e 敏感?
【问题讨论】:
-
你能说明一个带有空格或其他字符的单词应该如何映射吗?
-
@tobias_k 编辑了问题!
-
谢谢,但是“并且下一个字符没有被替换”应该是“并且下一个字符现在被替换”吗?为什么你以不同的方式处理空格和“不是字母”?你能添加一个带空格的例子吗?
标签: python dictionary replace duplicates