在Python中,有時需要將list以字符串的形式輸出,此時可以使用如下的形式:
",".join(list_sample)
1
其中,,表示的是分隔符
如需要將a_list = ["h","e","l","l","o"]轉換成字符輸出,可以使用如下的形式轉換:
a_list = ["h","e","l","l","o"]
print ",".join(a_list)
如果list中不是字符串,而是數字,則不能使用如上的方法,會有如下的錯誤:
TypeError: sequence item 0: expected string, int found
可以有以下的兩種方法:
1、
num_list = [0,1,2,3,4,5,6,7,8,9]
num_list_new = [str(x) for x in num_list]
print ",".join(num_list_new)
2、
num_list = [0,1,2,3,4,5,6,7,8,9]
num_list_new = map(lambda x:str(x), num_list)
print ",".join(num_list_new)
————————————————
版權聲明:本文為CSDN博主「zhiyong_will」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/google19890102/article/details/80932546