dinku33
dinku33

Reputation: 53

Python For loop on string is not printing any result

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

Answers (3)

Rob Streeting
Rob Streeting

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

mustafa kemal tuna
mustafa kemal tuna

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

ycx
ycx

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

Related Questions