Search code examples
startswith

Only print strings starting with a given letter / Python


print cites from visited_cities list in alphabetical order using .sort()

only print cities that names start "Q" or earlier (meaning a to q)

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]

the .sort() was easy to do but I don't know how figure out the second part of the problem.


Solution

  • you could do it with regular expressions and filtering like:

    import re
    regex=re.compile('[A-Q]{1}.*')
    cities = list(filter(lambda city: re.match(regex, city), visited_cities))
    print(*cities, sep='\n')
    

    the regex variable looks for any city starting from [A-Q]

    there is even an easier solution by utilizing the Unicode code point of a character. look at the method ord

    for city in visited_cities:
         first_character = city[0]
         if ord(first_character) >= ord('A') and ord(first_character) <= ord('Q'):
                 print(city)
    

    the Unicode code points are ordered so an A is at 65, B is at 66 ... Q is at 81 ... Z is at 90. so if you want to print only those cities starting with letters from A to Q you have to make sure their Unicode code point is between 65 and 81