python字符串转化列表_Python列表到字符串的转换[通俗易懂]

python字符串转化列表_Python列表到字符串的转换[通俗易懂]python字符串转化列表Sometimeswewanttoconvertthelisttoastringsothatwecanprintitorlogitfordebuggingpurposes.Inthistutorial,wewilllearnhowtoconvertalisttostringinaPythonpro…

大家好,又见面了,我是你们的朋友全栈君。

python字符串转化列表

Sometimes we want to convert the list to a string so that we can print it or log it for debugging purposes. In this tutorial, we will learn how to convert a list to string in a Python program.

有时我们希望将列表转换为字符串,以便我们可以打印或记录该列表以进行调试。 在本教程中,我们将学习如何在Python程序中将列表转换为字符串。

Python列表到字符串的转换 (Python List to String Conversion)

If the list contains a string, int, floats then its elements values are getting printed when we print the list.

如果列表包含字符串int浮点数,则在我们打印列表时将打印其元素值。

l1 = [1, 2, 3]
print(l1)

l1 = ['A', 'B', 'C']
print(l1)

l1 = ['A', 'B', 'C', 1, 2, 3.5]
print(l1)

Output:

输出:

[1, 2, 3]
['A', 'B', 'C']
['A', 'B', 'C', 1, 2, 3.5]

If you don’t want brackets in the output, you can use string strip() function or slicing to remove them.

如果不想在输出中使用括号,则可以使用字符串strip()函数或切片将其删除。

print(str(l1).strip('[]'))
print(str(l1)[1:-1])

Output:

输出:

'A', 'B', 'C', 1, 2, 3.5
'A', 'B', 'C', 1, 2, 3.5

Python对象列表到字符串的转换 (Python List of Objects to String Conversion)

Let’s see what happens when our list contains custom objects.

让我们看看列表包含自定义对象时会发生什么。

class Data:
    id = 0

    def __init__(self, i):
        id = i

l1 = [Data(10), Data(20)]
print(l1)

Output:

输出:

[<__main__.Data object at 0x10f3dd320>, <__main__.Data object at 0x10f3dd2e8>]

The information is not useful because it doesn’t contain any information about Data objects.

该信息无用,因为它不包含有关Data对象的任何信息。

When we print a list, it tries to invoke its elements __repr__() function. Since our object doesn’t define its own repr() function, its superclass object repr() is called which prints this information.

当我们打印列表时,它会尝试调用其元素__repr __()函数。 由于我们的对象没有定义自己的repr()函数,因此将调用其超类对象repr()来打印此信息。

Let’s define __repr__() function for Data class as follows:

让我们为Data类定义__repr __()函数,如下所示:

def __repr__(self):
        return f'Data[{self.id}]'

Now the output of above print statement will be:

现在,上述打印语句的输出将是:

[Data[0], Data[0]]

Sometimes an object defines only __str__() function and doesn’t define __repr__() function. In that case, we can convert the list to string by calling str() function on its elements.

有时,一个对象仅定义__str __()函数,而没有定义__repr __()函数。 在这种情况下,我们可以通过在其元素上调用str()函数将列表转换为字符串。

This can be done by using string join() function with an iterator as argument or by using map() function.

这可以通过使用带有迭代器作为参数的字符串join()函数或通过使用map()函数来完成

Let’s define __str__() function for Data class as:

让我们为Data类定义__str __()函数为:

def __str__(self):
        return f'D[{self.id}]'

Now we can get string representation of the list elements and print it using following code:

现在,我们可以获取列表元素的字符串表示形式,并使用以下代码进行打印:

print(', '.join(map(str, l1)))
print(', '.join(str(e) for e in l1))

Output:

输出:

D[0], D[0]
D[0], D[0]

Note that if __str__() function is not defined for an object, str() function fallback to calling __repr__() function. In that case __repr__() should return string object.

请注意,如果未为对象定义__str __()函数,则str()函数将回退到调用__repr __()函数。 在这种情况下,__repr __()应该返回字符串对象。

If we remove __str__() function from Data class, then above join() snippets output will be:

如果我们从Data类中删除__str __()函数,则以上join()片段输出将为:

Data[0], Data[0]
Data[0], Data[0]

We can specify our own delimiter when using join() function.

使用join()函数时,我们可以指定自己的定界符。

print('|'.join(map(str, l1)))
print('#'.join(str(e) for e in l1))

Output:

输出:

D[0]|D[0]
D[0]#D[0]
GitHub Repository.
GitHub存储库中检出完整的python脚本和更多示例。

翻译自: https://www.journaldev.com/23655/python-list-to-string-conversion

python字符串转化列表

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/142963.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • JDK1.8关于运行时常量池, 字符串常量池的要点[通俗易懂]

    JDK1.8关于运行时常量池, 字符串常量池的要点[通俗易懂]网上关于jdk1.8的各种实验,结论鱼龙混杂,很多都相矛盾,网上有的实验也被后人测试出了不同的结果很多都分辨不了真假,这里记录一下网络上正确的结论,欢迎指正!首先自行区分运行时常量池与Class文件常量池(静态常量池)的概念,JVM内存模型,方法区与永久代的区别,有些在我的其他博客有介绍,连接在文尾在JDK1.7之前运行时常量池逻辑包含字符串常量池存放在…

  • 小苏打俗称碳酸氢钠_碳酸氢钠俗称苏打还是小苏打

    小苏打俗称碳酸氢钠_碳酸氢钠俗称苏打还是小苏打小苏打介绍(化学方面叫碳酸氢钠) CAS:144-55-8  分子式:NaHCO3  分子量:84.01  中文名称:碳酸氢钠重碳酸钠小苏打酸式碳酸钠重曹  英文名称:Car

  • 安卓 Android之开发简单小应用(一)

    安卓 Android之开发简单小应用(一)安卓Android之开发简单小应用(一)一、简述  记–没学过Android之开发简单小应用。(课程设计作业)  例子打包:链接:https://pan.baidu.com/s/1LEQ1oWkUX8OmtfCFVydxWQ密码:9o0d二、环境搭建软件打包:链接:https://pan.baidu.com/s/1VVsZqPrwOtvMuzeeJE1y_A密…

  • Unity | Cinemachine ClearShot Camera[通俗易懂]

    Unity | Cinemachine ClearShot Camera[通俗易懂]ClearShotCamera可以管理一组子虚拟相机,这些虚拟相机需要具有CinemachineCollider组件,ClearShotCamera可以实现角色被障碍物挡住时,虚拟摄像机的自动切换效果,如下所示,角色与Cam2被BoxCollider挡住时,虚拟相机由Cam2自动切换到Cam3。ClearShotCamera上有一个CinemachineClearShot组件,VirtualCameraChildren管理虚拟相机。CinemachineCollider既可以挂在所

  • 数据库的概念模型,联系,E-R模型的设计方法「建议收藏」

    概念模型的基本概念:表示概念模型的最常用模型是实体-联系模型(Entity-RelationshipModel,简称E-R模型)E-R模型中,数据的结构被表示为“实体-联系”图。(E-R图)图中有三个主要的元素类型:实体集,属性和联系。联系:两个实体集之间的联系可归纳为以下三类:1)一对一联系(1:1) 2)一对多联系(1:n)和多对一联系(n:1)3)多对多联…

  • es6箭头函数详解_es6的新特性

    es6箭头函数详解_es6的新特性ES6标准新增了一种新的函数:ArrowFunction(箭头函数)。基础语法通常函数的定义方法varfn1=function(a,b){returna+b}functionfn2(a,b){returna+b}使用ES6箭头函数语法定义函数,将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号