0

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)
3
  • 5
    char == 'c' and char =='o' can never be true - a character only has a single value Commented Feb 17, 2019 at 15:53
  • You expression is equivalent to (char == 'c') and (char =='o') and (char in 'abcdefghijklmnopqrstuvwxyz') and (char == 'e') Commented Feb 17, 2019 at 15:54
  • 2
    Did you mean or instead of and? Commented Feb 17, 2019 at 15:56

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.