python - 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")
解决方案
replace()
返回字符串的副本,其中所有出现的子字符串都被替换。
您不能在 python 中改变(修改)字符串。即使你非常想要。字符串在设计上是不可变的数据类型,因此请创建一个新字符串。正确的使用是
string2 = string.replace(....
好吧,正如蒂埃里建议的那样,您可以将该新字符串存储在同一个变量中
string = string.replace(...
推荐阅读
- laravel-8 - SQLSTATE[HY000]:一般错误:1364 ----请帮助我使用 Laravel 8 解决它
- neo4j - 在 Neo4j 中添加与现有数据的关系
- powershell - PowerShell 中的日期时间无法转换我的时间
- reactjs - 在网络选项卡中显示但未在页面上显示时反应获取返回未定义
- netty - Grpc netty 处理程序库与 OpenJSSE 冲突
- python-3.x - 在 Unittest 中模拟 neo4j Record 实例
- python - matplotlib - 数据框 - 如何在 matplotlib 的背景上拥有真实地图
- machine-learning - 如何在经过训练的模型上使用新句子进行情感分析?
- excel - VBA 记录集不返回所有数据
- java - 环境变量 JAVA_HOME 未指向 Android Studio 中的有效 JVM