-1

I want to get all the words starting with a or A in a string printed.

But, this just prints all the elements. What should i do to solve it?

I have made the following:

string1= input("Enter a string: ")

words= string1.split()

for word in words:
    if(word[0]=='a' or 'A'):
        print(word)

This prints all the elements instead of just the letters starting with a or A.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    See https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value - `... or 'A'` is **always true**. – jonrsharpe Jan 31 '19 at 17:43

6 Answers6

1
string1= input("Enter a string: ")

words= string1.split()

for word in words:
    if(word[0]=='a' or word[0] == 'A'):
        print(word)

You did word[0] == 'a' or 'A', which always evaluate to true.
You can even use list comprehension like this:

a_words = [word for word in words if word[0] =='a' or word[0] == 'A']
taurus05
  • 2,491
  • 15
  • 28
1

You could do:

string1= input("Enter a string: ")

words= string1.split()

for word in words:
    if(word[0] in ['a', 'A']):
        print(word)

or with an even shorter if statement:

    if(word[0] in 'aA'):
poehls
  • 36
  • 4
0

Your test is incorrectly written. Right now it looks like this:

if(word[0]=='a' or 'A'):
    print(word)

But since 'A' isn't null, the loop is basically:

if(word[0]=='a' or True):
    print(word)

And it will always enter, because anything or True is True.

What you actually want is to test both against a and A, like this:

if(word[0]=='a' or word[0]=='A'):
    print(word)
Mikael Brenner
  • 357
  • 1
  • 7
0

Here, I fixed it

string1= input("Enter a string: ")

words= string1.split()

for word in words:
    if(word[0]=='a' or word[0]=='A'):
        print(word)

When you write like

if(word[0]=='a' or 'A'):

python evaluates word[0]=='a' separately and 'A' separately where 'A' is implicitly converted to true. Hence your condition is always true.

0

Try this:

>>> string= input("Enter a string: ")
Enter a string: a world of an Apple
>>> string
'a world of an Apple'
>>> words_starts_with_a_or_A = [word for word in string.split() if word.lower().startswith('a')]
>>> words_starts_with_a_or_A
['a', 'an', 'Apple']
han solo
  • 6,390
  • 1
  • 15
  • 19
0

Using the operator in:

s = input("Enter a string: ")

words = s.split()

for word in words:
    if word[0] in 'Aa':
        print(word)

Using the function any() with a generator comprehension and the method startswith():

s = input("Enter a string: ")

words = s.split()

for word in words:
    if any(word.startswith(i) for i in 'Aa'):
        print(word)

or with a comparison operator:

s = input("Enter a string: ")

words = s.split()

for word in words:
    if any(word[0] == i for i in 'Aa'):
        print(word)
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73