python中的字典键和字符串比较
我将dictionary键与预定义的字符串进行了比较,尽管看起来很相似,但比较总是失败。 例如:key='eng-101'和'eng-101'字符串不相同 请帮忙python中的字典键和字符串比较,python,django,Python,Django,我将dictionary键与预定义的字符串进行了比较,尽管看起来很相似,但比较总是失败。 例如:key='eng-101'和'eng-101'字符串不相同 请帮忙 for key, value in course_dict.items() : print('search ky is --'+key) print('the elective courses are---',courses) #finding the key in string
for key, value in course_dict.items() :
print('search ky is --'+key)
print('the elective courses are---',courses)
#finding the key in string
if(courses.find(key)==-1):
print('key not found--'+key)
else:
print('---------------------the key found is---'+key)
key=str(key +'-101,')
key=key.replace(' ','')
first_year_el_course+=key
print(elective_counter)
print(first_year_el_course)
print('newly formatter key--: '+key)
print(key=='eng-101')
更改:
key=str(key +'-101,') # Remove the comma at the end, otherwise key will be 'eng-101,' and not 'eng-101'.
致:
更改:
key=str(key +'-101,') # Remove the comma at the end, otherwise key will be 'eng-101,' and not 'eng-101'.
致:
@DipenDadhaniya是正确的,但使用字符串格式总是更好。这将使您的代码更加简洁易读 在迭代过程中更改迭代变量
key
时要小心,因为这有时会导致难以调试的意外后果。给它一个新名称,例如new\u key
new_key='{}-101'。格式(key.replace(''))
@dipendadaniya是正确的,但使用字符串格式总是更好。这将使您的代码更加简洁易读
在迭代过程中更改迭代变量key
时要小心,因为这有时会导致难以调试的意外后果。给它一个新名称,例如new\u key
new_key='{}-101'。格式(key.replace(''))
问题不太清楚。请添加输入和预期的o/p?输入字典的外观以及实际需要的内容等。此外,str()的使用是无用的,因为它已经在内部串联,因此最终结果将是字符串,因此不需要显式转换。如果您认为key不是string,那么语句应该是str(key)+'-101'
而不是str(key+'-101')
。问题不太清楚。请添加输入和预期的o/p?输入字典的外观以及实际需要的内容等。此外,str()的使用是无用的,因为它已经在内部串联,因此最终结果将是字符串,因此不需要显式转换。如果您认为key不是string,那么语句应该是str(key)+'-101'
而不是str(key+'-101')
。此外,str()的使用是无用的,因为它已经在内部串联,所以最终结果将是一个字符串,所以不需要显式转换。如果key不是string,那么语句应该是str(key)+'-101'
而不是str(key+'-101')
。此外,str()的使用是无用的,因为它已经在内部串联,所以最终结果将是一个字符串,所以不需要显式转换。如果key不是string,那么语句应该是str(key)+'-101'
而不是str(key+'-101')
。这不回答原始问题,应该作为注释发布。这不回答原始问题,应该作为注释发布