【问题标题】:Replace character to "@" in string将字符串中的字符替换为 \"@\"
【发布时间】:2022-11-12 07:31:34
【问题描述】:

为什么 python 不替换 @ 的最后一个字符?

str_manip = input("Enter a sentence ")
last_char = str_manip[-1]
print(last_char)
change_char = str_manip.replace("last_char", "@")
print(change_char)

它与我输入的句子完全相同,没有改变。

看了几个网站还是不明白。我想可能是因为 @ 是 char 但 str() 没有帮助,将其保存为单独的字符串变量也不起作用。

【问题讨论】:

  • 您在replace() 调用中的引号中有last_char,因此它正在寻找文字字符串last_char
  • 您正在更换文字串last_char。要将变量用作要替换的字符,只需不要在其周围加上引号。
  • str_manip.replace("last_char", "@") 在这里,您将 last_char 作为字符串传递。您需要传递一个名为 last_char 的变量,即不带任何引号,如下所示 str_manip.replace(last_char, "@")
  • 有用!如此简单但如此艰难 :D 谢谢大家!

标签: python replace


【解决方案1】:

尝试这个

str_manip = input("Enter a sentence ")
last_char = str_manip[-1]
print(last_char)
change_char = str_manip.replace(last_char, "@")
print(change_char)

【讨论】:

  • 谢谢!刚做了。
【解决方案2】:

从名为“last-char”的变量中删除引号

【讨论】:

    猜你喜欢
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多