在文本文件0.txt中,我有一行 “缩短了他在外线的长度,xxxx将其压过并防守到外线”。 我正在将这些数据存储到列表中
file = io.open('./commentry/0.txt','r',encoding="utf8")
for i in file.readlines():
zeroComm.append(i)
现在,我想从列表中获取该行,并通过向其传递变量在需要的时间和地点打印它。比如说
name = 'martian'
print(random.choice(zeroComm))
我需要像[名称代替xxxx]这样的输出 缩短了他在外线的长度,火星人将其压过并保护到外线
使用
str.replace
。这将用较大字符串中的另一个子字符串替换一个子字符串的所有实例这里的文档:https://docs.python.org/3/library/stdtypes.html#str.replace
你可以这样做
change_name(s, name)
接受两个字符串-s
和name
,用name
替换xxxx
,并返回替换的字符串请注意,这不会更改原始字符串
通过传入字符串
s
和name
,可以在任何需要的地方使用此函数应更换的零件是否始终为“xxxx”或定义良好的格式?然后您可以简单地使用您的string.replace('xxxx',thename),或者如果您想匹配一个模式而不是一个精确的字符串,可以使用regex子函数
另外,我不确定您正在读取的这些文本文件来自何处,但是如果您自己生成它们,您可以在创建它们时插入“{name}”,而不是“xxxx”,然后使用类似于
如果不能更改文本文件的格式,这显然不是一个解决方案
相关问题 更多 >
编程相关推荐