python - 如何将整数字符串与整数进行比较?
问题描述
我写了下面的代码:
d = 4
int_list = [1,2,3,4,5]
string_digits = [str(int) for int in int_list]
str_of_ints = ''.join(string_digits)
this produces -> str_of_ints = 1491625 (and this is a string)
for i in str_of_ints:
if i == 'd':
print("hello")
我遇到的问题是 i == 'd' 行;这是返回错误的-这是为什么?以及如何将字符串 1491625 与整数 5 进行比较,特别是如何检查 1491625 的任何数字是否等于 5?
我试过做:
for i in str_of_ints:
if i == d:
print("hello")
这当然行不通,因为那时我们会将字符串与整数进行比较?
解决方案
d
您的问题是在迭代时将整数与字符串进行比较str_of_ints
。您的数据类型必须匹配。4 与“4”不同。这可以通过使用以下str()
方法将搜索到的值转换为 str 来解决:
d = 4
int_list = [1,2,3,4,5]
string_digits = [str(int) for int in int_list]
str_of_ints = ''.join(string_digits)
# this produces -> str_of_ints = 1491625 (and this is a string)
if str(d) in str_of_ints:
print('hello')
推荐阅读
- android - 从android studio中的网站提取文本
- php - Wordpress:显示来自特定页面的子页面的图像附件
- python-3.x - 在 python3 中获取具有不同系统语言的桌面路径
- antlr - ANTLR4 意外的解析行为
- go - 为 TOML 文件和 golang 解析表中的键值对
- json - Swift/Alamofire:遍历 JSON 值以检查布尔值?
- python - 为什么 pd.concat 将结果类型从 int 更改为 object?
- go - 将标准输入复制到缓冲区
- python - 使用模板在 Flask 中没有数据刷新
- javascript - 循环遍历 2 数组并使用 onclick 获取项目