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)
上一篇 2022年5月10日 下午8:40
下一篇 2022年5月10日 下午9:00


相关推荐

  • @transactional的使用_@transactional注解默认的回滚方式

    @transactional的使用_@transactional注解默认的回滚方式@Transactional是声明式事务管理编程中使用的注解1.添加位置1)接口实现类或接口实现方法上,而不是接口类中。2)访问权限:public的方法才起作用。@Transactional注解应该只被应用到public方法上,这是由SpringAOP的本质决定的。系统设计:将标签放置在需要进行事务管理的方法上,而不是放在所有接口实现类上:只读的接口就不需要事务管…

    2026年4月19日
    4
  • app抓包工具_【旧版IPA抓包教程2】超便捷苹果旧版本APP抓包/轻松抓取你想要的版本,旧版app任意下载…

    app抓包工具_【旧版IPA抓包教程2】超便捷苹果旧版本APP抓包/轻松抓取你想要的版本,旧版app任意下载…之前呢就已经给大家发过一期抓包旧版ipa的教程,果然方法多种多样,今天又给大家带来一个更加简便快捷的的抓包软件,过程很简单,是个正常人都能学会,赶紧学起来吧~首先还是电脑一台,包含AppStore的iTunes的一个,旧版抓包程序一个,这次所需的工具就是多出来一个⛏镐子一样的玩意,这个程序是免费的,网上应该也能找到。也可以在文章末尾找到关键词回复下载。首先打开iTunes并登…

    2022年5月7日
    713
  • JAVA基本框架搭建(Maven,jetty,Joda-time,junit)

    JAVA基本框架搭建(Maven,jetty,Joda-time,junit)

    2021年5月11日
    125
  • python 生成数组_Python创建数组「建议收藏」

    python 生成数组_Python创建数组「建议收藏」1创建数组array函数>>>a=([1,2],[3,4])>>>array(a)array([[1,2],[3,4]])arange函数:指定初始值、终值、步长来创建数组>>>importnumpy>>>numpy.arange(0,1,0.1)array([0.,0.1,0.2,0.3,0.4…

    2022年5月9日
    296
  • 【Linux编程】三分钟让你学会Linux下用户密码更改

    【Linux编程】三分钟让你学会Linux下用户密码更改Linux 环境下密码更改包括两种 第一种 root 用户 管理员 密码更改第二种 非 root 用户 普通用户 密码更改可能需要进行密码更改的场景 购买云服务后 原始的 root 密码过于复杂 不方便记忆和使用 需要进行 root 密码更改 创建一个新的用户后 发现最初设置的密码不好管理 或者之前把这个账号分享给其他人 但是又想要收回账号 没啥事情 就是玩儿 一 root 用户密码更改总思路 要进行 root 密码更改 必须在 root 用户下进行 步骤一 前期准备 登录 root 用户我们可以直

    2026年3月17日
    2
  • 国内能用的国际邮箱推荐哪个?公司邮箱号码大全「建议收藏」

    国内能用的国际邮箱推荐哪个?公司邮箱号码大全「建议收藏」在网上看到大家一直在讨论国际邮箱哪个好用,TOM、163、gmail等,在国内用哪个邮箱呢?外贸公司需要跟客户沟通合同信息、物流货代公司需实时沟通货柜清关进展、电商公司采购出口需跟国外办事处或客户沟通、软件信息公司老板是老外,也必须用国际邮箱,这些使用邮箱的人90%都会在国内用邮箱,所以在国内能的国际邮箱是刚需。国内能用的国际邮箱推荐常用个人邮箱,但进了公司用企业邮箱才发现真的不一样。TOM企业邮箱是我在大学里看到老师用过的,现在公司分配了一个给我,之前的个人邮箱Facebook验证码都收不到,公司的这

    2026年2月26日
    4

发表回复

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

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