首页 > 解决方案 > 如何将整数字符串与整数进行比较?

问题描述

我写了下面的代码:

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") 

这当然行不通,因为那时我们会将字符串与整数进行比较?

标签: pythonstringlist

解决方案


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')

推荐阅读