Python 将列表值转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14016761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:11:50  来源:igfitidea点击:

Python turn list values into String

pythonlistpython-2.7

提问by user1869421

I've got the list values stored as:

我将列表值存储为:

country = [u'USA']

How can I turn it into just 'USA'. I've tried str(country), but it didn't work.

我怎么能把它变成“美国”。我试过了str(country),但没有奏效。

采纳答案by Ashwini Chaudhary

Apply str()on the element not on the list:

应用于str()不在列表中的元素:

In [206]: country = [u'USA']

In [207]: country[0] = str(country[0])

In [208]: country
Out[208]: ['USA']

or may be you meant this:

或者你可能是这个意思:

In [217]: country = [u'USA']

In [218]: country = str(country[0])

In [219]: country
Out[219]: 'USA'

回答by jfs

countryis a list that already contains Unicode strings. You don't need to convert it. The u''syntax is just the item representation as a Python literal (how you would type it in a Python source code).

country是一个已经包含 Unicode 字符串的列表。你不需要转换它。该u''语法只是项目表示为Python文字(你将如何在Python源代码中键入它)。

If you do need a bytestring; use .encode()method with an appropriate character encoding e.g.:

如果你确实需要一个字节串;使用.encode()具有适当字符编码的方法,例如:

b = country[0].encode("ascii")

In general, structure a text processing code as Unicode sandwichi.e., use Unicode internally and use bytes only to communicate with outside world; don't mix the two.

一般情况下,将文本处理代码构造为Unicode三明治,即内部使用Unicode,仅使用字节与外部世界进行通信;不要将两者混为一谈。