字符串上的Python For循环未打印任何结果
我使用For循环创建一个新字符串,但它不会打印任何结果字符串上的Python For循环未打印任何结果,python,Python,我使用For循环创建一个新字符串,但它不会打印任何结果 new_str = '' for char in 'dfdfadcodefgldfjdcodefdfepiddjcode': if char == 'c' and char =='o' and char in 'abcdefghijklmnopqrstuvwxyz' and char == 'e': new_str += char print (new_str) 请注意,通过使用和,当您的代码计算出一个假时,
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char == 'c' and char =='o' and char in 'abcdefghijklmnopqrstuvwxyz' and char == 'e':
new_str += char
print (new_str)
请注意,通过使用
和
,当您的代码计算出一个假
时,它将跳过该条件
比如说,
s = 'd'
if s == 'c' and s == 'd':
print ('pass')
else:
print ('fail')
上述代码将打印'fail'
,因为s
使第一个s=='c'
部分失败。但是,如果您更改为:
s = 'd'
if s == 'c' or s == 'd':
print ('pass')
else:
print ('fail')
上面的代码将打印'pass'
,因为s
使第一个s=='c'
部分失败,但将继续计算第二个s=='d'
部分
现在,如果您只想从字符串中排除'c','o','e'
,只需将它们从部分中删除即可:
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char in 'abdfghijklmnpqrstuvwxyz':
new_str += char
print (new_str)
或者你可以:
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char not in 'coe':
new_str += char
print (new_str)
我认为您希望从字符串中删除“c”、“o”和“e”字符。如果我的假设是正确的,那么你可以使用这个片段
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char != 'c' and char !='o' and char in 'abcdefghijklmnopqrstuvwxyz' and char != 'e':
new_str += char
print (new_str)
new_str
为空,因为if
条件的计算结果永远不会为true。如果意图是在字符与指定的字符之一匹配时追加字符,则需要使用或,而不是和char=='c'和char=='o'
永远不能为真-一个字符只有一个值表达式等价于(char=='c')和(char=='o'),并且(char在'abcdefghijklmnopqrstuvxyz'中)和(char='e')
您是指还是而不是和?