将不同类型的项目列表作为字符串加入Python [英] Join a list of items with different types as string in Python

查看:85
本文介绍了将不同类型的项目列表作为字符串加入Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加入项目列表.列表中的许多项目都是从函数返回的整数值;即

I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,

myList.append(munfunc()) 

我应该如何将返回的结果转换为字符串以使其与列表结合?

How should I convert the returned result to a string in order to join it with the list?

是否需要对每个整数值执行以下操作:

Do I need to do the following for every integer value:

myList.append(str(myfunc()))

有没有更多的Python方式可以解决投放问题?

Is there a more Pythonic way to solve casting problems?

推荐答案

调用str(...)是将内容转换为字符串的Python方法.

Calling str(...) is the Pythonic way to convert something to a string.

您可能需要考虑为什么要使用字符串列表.您可以改为将其保存为整数列表,并且仅在需要显示整数时才将其转换为字符串.例如,如果您有一个整数列表,则可以执行以下操作:

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can do this:

print ', '.join(str(x) for x in list_of_ints)

这篇关于将不同类型的项目列表作为字符串加入Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆