To compare the first letter of a Python string.

Asked 2 years ago, Updated 2 years ago, 20 views

list: [Apple, Pineapple, Graph] How should I write a program that outputs the element with the letter A to O?

For range, you can only enter numbers, so I put the alphabet in range, and there is an error.

python

2022-09-21 11:33

2 Answers

import string

upper_letter = string.ascii_uppercase
print(upper_letter) # 'ABCDEF...WXYZ'
start = upper_letter.index('A')
end = upper_letter.index('O')
values = ['Apple', 'Pineapple', 'Grape'] 
for value in values:
    for i in range(start, end):
        if value[0] == upper_letter[i]:
            print(value)
            break

'string' is a built-in library.
You can get alphabetic case here.
Check the alphabet to see what number of letters 'A', 'O' are.
Take out the values of values one by one in the for loop.
The inner loop verifies that the first letter of the value is 'A' to 'O'.
If so, print it out and stop checking any more and move on to another value.

If the values of values are case-sensitive, you can capitalize the first letter as follows.

values = ['apple', 'pineapple', 'grape'] 
for value in values:
    print(value.capitalize())


2022-09-21 11:33

ord Simple pool using built-in functions. ord returns the index number of the Unicode character table when you insert a character.

fruits = ["Apple", "Pineapple", "Grape"]

for fruit in fruits:
    if ord("A") <= ord(fruit[0]) <= ord("O"):
        print(fruit)


2022-09-21 11:33

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.