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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • echarts数据可视化如何实现_数据可视化页面

    echarts数据可视化如何实现_数据可视化页面ECharts实现数据可视化入门教程(超详细)ECharts介绍ECharts入门教程第一步:下载并引入scharts.js文件第二步:编写代码目录结构编写index.html代码效果展示ECharts的基础配置主要配置(常用的)案例讲解ECharts介绍官网链接:ApacheEChartsECharts是一个使用JavaScript实现的开源可视化库,可以流畅的运行在PC和移动设备上,兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Safari等),底层依赖矢

    2022年10月12日
  • python无人机编程_3d硬金是什么意思

    python无人机编程_3d硬金是什么意思往期本文是双足机器人系列的第三篇,在前面的文章中我们介绍了2D线性倒立摆的基本理论,详见:【双足机器人(1)】线性倒立摆及其运动控制(附代码)在这篇文章中我们要详细介绍3D线性倒立摆的基本…

    2022年8月18日
  • datagroup激活码[最新免费获取]

    (datagroup激活码)2021最新分享一个能用的的激活码出来,希望能帮到需要激活的朋友。目前这个是能用的,但是用的人多了之后也会失效,会不定时更新的,大家持续关注此网站~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月31日
  • Python中字符串String去除出换行符(\n,\r)和空格的问题

    Python中字符串String去除出换行符(\n,\r)和空格的问题Python中字符串String去除出换行符和空格的问题(\n,\r)在Python的编写过程中,获取到的字符串进场存在不明原因的换行和空格,如何整合成一个单句,成为问题。方法:一、去除空格“·”代表的为空格  strip()"···xyz···".strip()#returns"xyz""···xyz···".lstrip()…

    2022年6月18日
  • SIGABRT 报错时的注意事项和解决方法

     SIGABRT报错,可以理解为安卓系统为保护自身安全,清理了你的应用,这样导致的应用崩溃,通常是在读取file或者结束某个逻辑操作时,没有及时的释放资源,这样会导致报错。我接触到这个崩溃问题,是因为需要多次频繁的加载webview时导致的,在ondestroy方法里,加上webview.destroy(),此时崩溃的次数明显减少,但是偶有崩溃,查找了网上很多答案,都未能解决问题,这时突然想到…

    2022年4月16日
  • 死锁的产生条件和预防处理[通俗易懂]

    死锁的产生条件和预防处理

    2022年1月21日

发表回复

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

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