如何在Python中将任何数据类型更改为字符串

问题:如何在Python中将任何数据类型更改为字符串

如何在Python中将任何数据类型更改为字符串?

How can I change any data type into a string in Python?


回答 0

myvariable = 4
mystring = str(myvariable)  # '4'

另外,也可以尝试repr:

mystring = repr(myvariable) # '4'

这在python中称为“转换”,非常普遍。

myvariable = 4
mystring = str(myvariable)  # '4'

also, alternatively try repr:

mystring = repr(myvariable) # '4'

This is called “conversion” in python, and is quite common.


回答 1

str旨在产生对象数据的字符串表示形式。如果您正在编写自己的类,并且想str为您工作,请添加:

def __str__(self):
    return "Some descriptive string"

print str(myObj)会打电话给myObj.__str__()

repr是类似的方法,通常会产生有关类信息的信息。对于大多数核心库对象,repr在尖括号之间生成类名称(有时会生成一些类信息)。repr例如,仅通过在“交互”窗格中键入对象即可使用,而无需使用print或其他任何方法。

您可以repr为自己的对象定义行为,就像可以定义以下对象的行为一样str

def __repr__(self):
    return "Some descriptive string"

>>> myObj在“交互”窗格中,或repr(myObj),将导致myObj.__repr__()

str is meant to produce a string representation of the object’s data. If you’re writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()


回答 2

我看到所有建议使用的答案str(object)。如果您的对象包含多个ascii字符,则可能会失败,并且您会看到类似的错误ordinal not in range(128)。在我用英语以外的其他语言转换字符串列表时,情况就是这样

我通过使用解决了 unicode(object)

I see all answers recommend using str(object). It might fail if your object have more than ascii characters and you will see error like ordinal not in range(128). This was the case for me while I was converting list of string in language other than English

I resolved it by using unicode(object)


回答 3

str(object) 会成功的

如果要更改对象的字符串化方式,请__str__(self)为对象的类定义方法。这种方法必须返回str或unicode对象。

str(object) will do the trick.

If you want to alter the way object is stringified, define __str__(self) method for object’s class. Such method has to return str or unicode object.


回答 4

使用str内置的:

x = str(something)

例子:

>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'

...

从文档中:

返回一个字符串,其中包含对象的可很好打印的表示形式。对于字符串,这将返回字符串本身。与repr(object)的区别在于str(object)并不总是尝试返回eval()可接受的字符串;它的目标是返回可打印的字符串。如果未提供任何参数,则返回空字符串“”。

Use the str built-in:

x = str(something)

Examples:

>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'

...

From the documentation:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ”.


回答 5

str(x)。但是,每种数据类型都可以定义自己的字符串转换,因此这可能不是您想要的。

With str(x). However, every data type can define its own string conversion, so this might not be what you want.


回答 6

您可以%s如下使用

>>> "%s" %([])
'[]'

You can use %s like below

>>> "%s" %([])
'[]'

回答 7

只需使用str-例如:

>>> str([])
'[]'

Just use str – for example:

>>> str([])
'[]'

回答 8

使用格式:

"%s" % (x)

例:

x = time.ctime(); str = "%s" % (x); print str

输出: 2018年1月11日星期四20:40:05

Use formatting:

"%s" % (x)

Example:

x = time.ctime(); str = "%s" % (x); print str

Output: Thu Jan 11 20:40:05 2018


回答 9

如果您确实要“更改”数据类型,请小心。像在其他情况下(例如,在for循环中更改迭代器),这可能会引起意外的行为:

>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18

Be careful if you really want to “change” the data type. Like in other cases (e.g. changing the iterator in a for loop) this might bring up unexpected behaviour:

>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18