简体   繁体   English

如何在python中引用变量?

[英]how can I quote a variable in python?

I don't know how to explanation my issue,here is code and error: 我不知道如何解释我的问题,这里是代码和错误:

html_title = 'abc'
file_name = html_title, '.txt'
html_write_to_file = open(file_name, 'wt')
...
...
...

error: 错误:

TypeError: coercing to Unicode: need string or buffer, tuple found

I notice that file_name must add quotation marks like this 我注意到file_name必须添加这样的引号

html_write_to_file = open('file_name', 'wt')

when I add quotation marks,the Variable functions does not work in open('file_name', 'wt') 当我添加引号时,变量函数在open('file_name', 'wt')不起作用

but I have to use filename format like this: html_title, '.txt' 但我必须使用这样的文件名格式: html_title, '.txt'

I don't know how to do... 我不知道怎么办......

Supplementary question: 补充问题:

characters are Japanese or Chinese,I tried encode to utf-8,still not work well. 字符是日文或中文,我尝试编码为utf-8,仍然不能正常工作。

You create a tuple here: 你在这里创建一个元组

file_name = html_title, '.txt'

The comma makes it a tuple; 逗号使它成为一个元组; here you created a tuple with two elements. 在这里你创建了一个包含两个元素的元组。 You then pass that tuple to the open() command: 然后,您将该元组传递给open()命令:

html_write_to_file = open(file_name, 'wt')

which complains that it can only take a string; 抱怨它只能拿一根绳子; it tells you that a tuple is not acceptable. 它告诉你一个元组是不可接受的。

You probably just wanted to add .txt to the html_title string, so use + to concatenate the strings: 您可能只是想将.txt添加到html_title字符串中,因此使用+来连接字符串:

file_name = html_title + '.txt'

Now file_name is a string object too. 现在file_name也是一个字符串对象。

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

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