需要有关 Python 中元组的帮助 [英] Need help with tuples in python

查看:34
本文介绍了需要有关 Python 中元组的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打印元组 (u'1S²') 我得到 1S² 的预测输出

When I print the tuple (u'1S²') I get the predicted output of 1S²

但是,当我打印元组 (u'1S²',u'2S¹') 我得到输出 (u'1S\xb2', u'2S\xb9').

However, when I print the tuple (u'1S²',u'2S¹') I get the output (u'1S\xb2', u'2S\xb9').

这是为什么?我该怎么办?
另外,如何获取元组中的项目数?

Why is this? What can I do about this?
Also, how do I get the number of items in a tuple?

推荐答案

表达式 (u'1S²') 不是 tuple,而是 unicode 值.一个 1 元组在 Python 中是这样写的:(u'1S²',).

The expression (u'1S²') is not a tuple, it's a unicode value. A 1-tuple is written in Python this way: (u'1S²',).

print value 语句实际上打印了一个 str(value).如果你需要输出多个 unicode 字符串,你应该使用这样的:

The print value statement prints a str(value) in fact. If you need to output several unicode strings, you should use something like this:

print u' '.join((u'1S²',u'2S¹'))

尽管字符编码可能存在问题.如果您知道您的控制台编码,您可以手动将 unicode 值编码为 str:

Though there might be issues with character encodings. If you know your console encoding, you may encode your unicode values to str manually:

ENCODING = 'utf-8'
print u' '.join((u'1S²',u'2S¹')).encode(ENCODING)

可以使用len函数获取元组、列表、字符串等序列中的iterm数.

The number of iterms in tuples, lists, strings and other sequences can be obtained using len function.

这篇关于需要有关 Python 中元组的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆