python - 使用 .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
我不明白我做错了什么。对此问题的任何帮助表示赞赏。
解决方案
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)
推荐阅读
- c# - 图表自动滚动(示波器效果)
- c++ - C++ 在运行时构建嵌套函数
- java - 无法使用 selenium webdriver 在 Gmail 中单击撰写按钮
- angular - 是否可以将 angularfire2 与 Angular 6 一起使用?
- php - 无法安装phpunit,结论:不要安装phpunit/phpunit 6.5.8
- bash - 如何使用 grep 模式匹配迭代移动文件/文件夹
- android - 安卓。如何在TextView中的一段文本中设置事件点击
- laravel - 使用不可为空字段的默认值进行更新
- python - 使用 python 构建没有 SKlearn 的多类逻辑回归分类器
- android - 使用 getSupportActionBar() 的简单操作栏 - 添加主页 < 和设置图标