简体   繁体   English

如何将变量的值作为字符串的一部分打印到文件中?

[英]How do I print the value of a variable to a file as part of a string?

If I have: 如果我有:

a=10
b = 20

how do I write 10 and 20 separated by a tab to the file? 如何将由制表符分隔的1020写入文件? Doing: 这样做:

myfile.write('a\tb')

just prints the literal string to the file. 只是将文字字符串打印到文件中。 How to substitute the values of a and b into the string? 如何将ab的值替换为字符串?

Python does not recognize variable names inside a string literal. Python无法识别字符串文字内的变量名称。 Instead, it treats them as normal text. 相反,它将它们视为普通文本。

In order to do what you want, you can use str.format : 为了做你想做的,你可以使用str.format

myfile.write('{}\t{}'.format(a, b))

This will take the values of a and b , convert them into strings, and then insert them into the string '{}\\t{}' . 这将采用ab的值,将它们转换为字符串,然后将其插入字符串'{}\\t{}' The curly braces {} denote where the values will be inserted. 大括号{}表示将在何处插入值。

他们必须不在''

myfile.write(str(a)+'\t'+str(b))

This is a pythonic way of doing it 这是一种Python方式

with open('Filename.fileformat', 'w') as f:
    a="10"
    b="20"
    lst = [a,b]
    for i in lst:
        print ''.join(i)
        f.write(str(''.join(i)) +'\n')

您可以轻松地使用格式化字符串

myfile.write('%d\t%d' % (a, b))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM