从文本文件中获取数据,并在打印前向其中添加变量

2024-09-30 00:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在文本文件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]这样的输出 缩短了他在外线的长度,火星人将其压过并保护到外线


Tags: 数据iniotxt列表foropenutf8
3条回答

使用str.replace。这将用较大字符串中的另一个子字符串替换一个子字符串的所有实例

string = " shortens his length outside off, xxxx presses across and defends it to the off-side "
name = "martian"
print(string.replace("xxxx", name))

这里的文档:https://docs.python.org/3/library/stdtypes.html#str.replace

你可以这样做

change_name(s, name)接受两个字符串-sname,用name替换xxxx,并返回替换的字符串

请注意,这不会更改原始字符串

通过传入字符串sname,可以在任何需要的地方使用此函数

lst = [" shortens his length outside off, xxxx presses across and defends it to the off-side ."]

# Replaces xxxx with name passed to argument and returns the string.
def change_name(s, name):
    return s.replace('xxxx', name)

print(change_name(lst[0], 'martian'))

应更换的零件是否始终为“xxxx”或定义良好的格式?然后您可以简单地使用您的string.replace('xxxx',thename),或者如果您想匹配一个模式而不是一个精确的字符串,可以使用regex子函数

另外,我不确定您正在读取的这些文本文件来自何处,但是如果您自己生成它们,您可以在创建它们时插入“{name}”,而不是“xxxx”,然后使用类似于

print("Hello {name}".format(name='Martin'))

如果不能更改文本文件的格式,这显然不是一个解决方案

相关问题 更多 >

    热门问题