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字符串转化列表

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • origin 2018安装教程与安装包

    origin 2018安装教程与安装包百度网盘地址:链接:https://pan.baidu.com/s/11Lo7R4YvldtkcKZxb5vbXQ提取码:aq8o这里是安装包大概1.8G,比较大。如果链接失效可以联系我913121976@qq.com邮箱。有什么问题可以一起交流!1、打开安装文件夹里的setup,进行安装。点击下一步2、同意许可,下一步。点击下一步3、客户信息,前两个可以随便填写,第三个…

    2022年4月27日
    96
  • ensp二层交换机不同vlan之间如何通信_华三交换机不同网段互通

    ensp二层交换机不同vlan之间如何通信_华三交换机不同网段互通ensp模拟交换机不同VLAN不同网段之间互通

    2022年9月11日
    1
  • mysql读写分离原理详解(主从复制和读写分离)

    主库记录二进制日志。在每次准备提交事务完成数据更新前,主库将数据更新的事件记录到二进制日志中。MySQL会按事务提交的顺序而非每条语句的执行顺序来记录二进制日志。在记录二进制日志后,主库会告诉存储引擎可以提交事务了。下一步,备库将主库的二进制日志复制到其本地的中继日志中。首先,备库会启动一个工作线程,称为I/O线程,I/O线程跟主库建立一个普通的客户端连接,然后在主库启动一个特殊的二进制转储线程,…

    2022年4月10日
    38
  • 7-9 集合相似度 给定两个整数集合,它们的相似度定义为:N ​c ​​ /N ​t ​​ ×100%。其中N ​c ​​ 是两个集合都有的不相等整数的个数,N ​t ​​ 是两个集合一共有的不相「建议收藏」

    7-9 集合相似度 给定两个整数集合,它们的相似度定义为:N ​c ​​ /N ​t ​​ ×100%。其中N ​c ​​ 是两个集合都有的不相等整数的个数,N ​t ​​ 是两个集合一共有的不相「建议收藏」7-9 集合相似度 给定两个整数集合,它们的相似度定义为:N ​c ​​ /N ​t ​​ ×100%。其中N ​c ​​是两个集合都有的不相等整数的个数,N ​t ​​ 是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。输入格式: 输入第一行给出一个正整数N(≤50),是集合的个数。随后N行,每行对应一个集合。每个集合首先给出一个正整数M(≤10 ​4 ​​)…

    2022年8月18日
    11
  • java中的向上取整和向下取整

    java中的向上取整和向下取整向上取整:比自己大的最小整数。向下取整:比自己小的最大整数。publicclassRoundingUp{publicstaticvoidmain(String[]args){System.out.println(Math.ceil(1.5));//2.0System.out.println(Math.ceil(-1.5));//…

    2022年6月21日
    62
  • 腾讯云服务器如何安装宝塔_服务器宝塔面板是什么

    腾讯云服务器如何安装宝塔_服务器宝塔面板是什么宝塔面板是一款服务器管理软件,用户可以通过Web端轻松管理服务器,提升运维效率。例如:创建管理网站、FTP、数据库,拥有可视化文件管理器,可视化软件管理器,可视化CPU、内存、流量监控图表,计划任务等功能。首先,开放腾讯云服务器宝塔端口:点进来后,点击防火墙:可以看到我们的服务器仅开放了……

    2022年10月20日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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