Home > Back-end >  python uppercase letters-the same location gets printed more than once if there is more than one ins
python uppercase letters-the same location gets printed more than once if there is more than one ins

Time:06-23

I want to print the location of all uppercase characters in a sentence, but I don't know why, if the same letter is capitalized more than once in the same sentence, this loop keeps printing out the first location.

In this sentence, the capital letter 'H' appears twice and I expect to print the following indices:

0 7 12 16

but instead, I print 0 7 12 0

sentence= 'Have a Nice Day Hey'
for i in sentence:
    if i.isupper():
        print(sentence.index(i),i)

CodePudding user response:

This is a more pythonic way to do the same thing that outputs correctly:

sentence= 'Have a Nice Day Hey'
for index, letter in enumerate(sentence):
    if letter.isupper():
        print(index, letter)

Check out enumerate function in the Python Docs

CodePudding user response:

Using str.index() returns the first occurrence of the character, so sentence.index('H') would always return 0 for your example.

More information here: https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

s.index(x[, i[, j]]) - index of the first occurrence of x in s 
                       (at or after index i and before index j)

What you want is to iterate over the list with a counter (or enumerate) and use the counter for your output:

sentence= 'Have a Nice Day Hey'
c = 0
for i in sentence:
  if i.isupper():
    print(c)
  c  = 1

CodePudding user response:

sentence.index(i) always gives first appearance of the letter in the sentence. Try using index, while looping:

for i in range(len(sentence)):
    if sentence[i].isupper():
        print(i, sentence[i])

CodePudding user response:

Use enumerate to access both the item and the index, and list comprehension. This is easier and faster than iterating over the string for each character, and then iterating over the string again to find the index of this character.

sentence = 'Have a Nice Day Hey'
upper_idxs = [i for i, c in enumerate(sentence) if c.isupper()]
print(upper_idxs)
# [0, 7, 12, 16]

CodePudding user response:

Ok so :

sentence= 'Have a Nice Day Hey'

You need to store the information about you getting the the first upper case somewhere. Let use a table

ifoundx = []
for i in sentence:
   if i.isupper() and i not in ifoundx :
       print(index, letter)
       ifoundx.append(i)

It should work

  • Related