首页 > 解决方案 > 使用 .join() 将列表值转换为在 python 中面临错误的字符串

问题描述

我正在尝试将列表的元素转换为单个字符串,但不知何故它不起作用;这是我的代码:

def dec_to_bin(num):
    bin_num = []

    while num > 1:
        bin_num.append(num % 2)
        num = num // 2

    if num == 1:
        bin_num.append(1)

    return(bin_num[::-1])

sample = dec_to_bin(19)
converted = " "
print(converted.join(sample))

当我运行程序时,我看到了这个错误:

TypeError: sequence item 0: expected str instance, int found

我不明白我做错了什么。对此问题的任何帮助表示赞赏。

标签: pythonstringlist

解决方案


def dec_to_bin(num):
    bin_num = []

    while num > 1:
        bin_num.append(num % 2)
        num = num // 2

    if num == 1:
        bin_num.append(1)

    return(bin_num[::-1])

sample = dec_to_bin(19)
ans = ("".join(str(x) for x in sample))
print(ans)

推荐阅读