首页 > 解决方案 > Python用相同的字符串替换不起作用?

问题描述

以下代码应采用#d# 形式的字符串并根据骰子滚动一个随机数,然后将#d# 替换为#。

例如,1d6 将掷出 1 个 6 面骰子并将 1d6 替换为 5。

# Turn dice notation into a number
def parse_dice(string):
# Replace all dice notations #d# with a number #
matches = re.findall("[0-9]+d[0-9]+", string)
for match in matches:
    a = match.split("d", 1)[0]
    b = match.split("d", 1)[1]
    roll = str(roll_dice(int(a), int(b)))
    print("String is: " + string + "\nThe match is: " + match + "\nI'll replace it with the roll: " + roll)
    string.replace(match, roll)
    print("After replacing I got: " + string)
# Parse any leftover math tacked on
number = eval(string)
return number

打印语句用于测试。这是一个示例输出:

String is: 1d6
The match is: 1d6
I'll replace it with the roll: 2
After replacing I got: 1d6 

出于某种原因,即使字符串与我要替换的字符串完全匹配,它也不会替换它,所以最后我运行的是 eval("1d6") 而不是 eval("5")

标签: pythonstringreplace

解决方案


replace() 返回字符串的副本,其中所有出现的子字符串都被替换。

您不能在 python 中改变(修改)字符串。即使你非常想要。字符串在设计上是不可变的数据类型,因此请创建一个新字符串。正确的使用是

string2 = string.replace(....

好吧,正如蒂埃里建议的那样,您可以将该新字符串存储在同一个变量中

string = string.replace(...

推荐阅读