Reputation: 53
I am using For loop to create a new string, but it is not printing any result.
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)
Upvotes: 0
Views: 61
Reputation: 1735
new_str
is empty, because the if
condition never evaluates to true. If the intention is that the the character is appended if it matches one of the specified characters, you'll need to use or
rather than and
.
Upvotes: 0
Reputation: 1129
I think you want to remove 'c' , 'o' and 'e' characters from string. If my assumption is ture then tou can use this snippet.
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)
Upvotes: 0
Reputation: 3211
Do note that by using and
, the moment your code evaluates a False
, it will skip that condition.
For example,
s = 'd'
if s == 'c' and s == 'd':
print ('pass')
else:
print ('fail')
The above code will print 'fail'
because s
has failed the first s == 'c'
part.
However, if you change to:
s = 'd'
if s == 'c' or s == 'd':
print ('pass')
else:
print ('fail')
The above code will print 'pass'
because s
has failed the first s == 'c'
part but will go on to evaluate the second s == 'd'
part.
Now if you wish to simply exclude 'c', 'o', 'e'
from your string, simply remove them from the in
part:
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char in 'abdfghijklmnpqrstuvwxyz':
new_str += char
print (new_str)
Or you could:
new_str = ''
for char in 'dfdfadcodefgldfjdcodefdfepiddjcode':
if char not in 'coe':
new_str += char
print (new_str)
Upvotes: 1