简体   繁体   English

使用python打印unicode文本

[英]Printing unicode text with python

I have a dictionary that is filled with lists where the data was read from an excel file. 我有一本字典,里面装满了从Excel文件中读取数据的列表。 All of the text is unicode however I do not have any special characters. 所有的文本都是unicode,但是我没有任何特殊字符。 I am trying to write the data that is located in the lists to a .txt file but I'm having trouble printing the lists out. 我正在尝试将列表中的数据写入.txt文件,但无法打印出列表。

target.write("move % to 100 100") % product[1][0]
target.write("\n move % to 200 100") % product[1][1]
target.write("\n connect % to %") % (product[1][0], product[1][1])

product is the dictionary that holds the multiple lists. product是包含多个列表的字典。 is there an easy way to format my .write statement so it can accept unicode. 有没有一种简单的方法来格式化.write语句,以便它可以接受unicode。 the error I'm getting is 我得到的错误是

"Type Error: unsupported operand type(s) for %: 'Nonetype' and 'unicode'

我只是个白痴,发现我可以键入强制转换产品,因此str(product [1] [0])可以满足我的需求

The error is coming from the parameters to the format strings not being inside the write parentheses. 错误是由于参数引起的,而不是格式字符串不在write括号内。 target.write(...) returns None so you are effectively processing: target.write(...)返回None因此您正在有效地处理:

None % product[1][0]

Another problem '%' is not a string formatting command by itself. 另一个问题'%'本身不是字符串格式化命令。 %s is probably what you want. %s可能就是您想要的。 If you are using Python 2.X your format strings are not Unicode. 如果您使用的是Python 2.X,则格式字符串不是 Unicode。 Add u in front of the strings. 在字符串前面添加u

Here's the fixes: 解决方法如下:

target.write(u"move %s to 100 100" % product[1][0])
target.write(u"\n move %s to 200 100" % product[1][1])
target.write(u"\n connect %s to %s" % (product[1][0], product[1][1]))

Or use the new .format method: 或使用新的.format方法:

target.write(u"move {} to 100 100".format(product[1][0]))
target.write(u"\n move {} to 200 100".format(product[1][1]))
target.write(u"\n connect {} to {}".format(product[1][0], product[1][1]))

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

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