Python:替换字符串中的特定字符(重复项的问题)

您所在的位置:网站首页 python字符串重复项 Python:替换字符串中的特定字符(重复项的问题)

Python:替换字符串中的特定字符(重复项的问题)

2024-07-14 12:02| 来源: 网络整理| 查看: 265

我有一个程序的代码,它将字符串中的字符替换为上标字符,每次跳过1个字符。

不在我的字典中的字符应该被跳过,但也会影响下一个字符是否将被替换(因此,如果" not - in -dict- character“应该被替换,它将被跳过,并且下一个字符不会被替换,反之亦然)

在不改变下一个字符的情况下,应跳过空格。

代码语言:javascript复制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)

问题是,如果replace函数试图替换的字符在字符串中有重复,它并不关心哪个字符是'e‘,而只是替换字符串中的第一个字符。

因此,如果用户输入'abaaba‘和'f',结果将是'ᵃᵇᵃaba’,而它应该是'ᵃbᵃaᵇa‘。有没有办法让替换对字符串中的哪个字符是e敏感?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3