Python Forum
startswith() function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: startswith() function (/thread-8746.html)



startswith() function - milo204 - Mar-05-2018

hi, im new to coding hence i have a rather simple problem!
im trying to sort a list of cities, so that for cities that start with a letter greater than Q, the city name is removed from the list.
My code runs but i dont seem to get the correct output.
How can i specify startswith greater than Q?
many thanks for your help.


visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
sorted_cities=sorted(visited_cities)
print(sorted_cities)

for x in sorted_cities:
    if x>="Q":
        sorted_cities.remove(x)
    else:
        pass
print(sorted_cities)



RE: startswith() function - mpd - Mar-05-2018

You're trying to compare the whole word (x) to one letter. You want to look at the first letter of the word (strings support the [] operator).


RE: startswith() function - DeaD_EyE - Mar-05-2018

Small change:
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
unique_visited_cities = set(visited_cities)
sorted_cities = sorted(unique_visited_cities)
print('All sorted cities:',sorted_cities)

cities_till_q = []
for city in sorted_cities:
    if city[0].lower() > 'q':
       break
    cities_till_q.append(city)

print('Sorted cities till q (inclusive):', cities_till_q)
The function set comes from set theory. A set has only unordered unique elements.
Sets are very useful:
set(['A', 'B', 'C']) & set(['X', 'Y', 'A', 'Z', 'U'])
We get only elements, which are in both sets.
Output:
{'A'}
Instead of running the loop on module level, make a function to be more flexible.
def get_cities(unsorted_cities, letter)
    ret = []
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        ret.append(city)
    return ret
Next iteration should be a docstring.
def get_cities(unsorted_cities, letter)
    """
    Returns a new list of unsorted cities.
    Cities which letter is bigger than the given letter
    are filtered.
    """
    ret = []
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        ret.append(city)
    return ret
Instead of creating inside the function a new list, you can also make a generator.
Lesser code, only one different statement and more flexibility.
def get_cities(unsorted_cities, letter):
    """
    Iterates over unsorted cities and
    yield cities, where the first letter
    is bigger than letter.
    """
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        yield city


# you have to call the function to get the generator (lazy)
# Then you need to consume the generator.
# You can use the generator in a for-loop
# or you use functions where the constructor
# iterates over the argument

list(get_cities(sorted_cities, 'q'))
list(get_cities(sorted_cities, 'h'))
list(get_cities(unsorted_cities, 'h'))
list(get_cities(unique_visited_cities, 'h'))



RE: startswith() function - milo204 - Mar-06-2018

Thats great thank you so much for explaining all of this!
Never heard of the set function so thank you for introducing it


RE: startswith() function - DeaD_EyE - Mar-06-2018

I found the set function very late. The story behind was: I needed a function to get rid of all duplicates, which were in another list. The task was to compare if a directory has changed files which differs from original and then it was synchronizing them. First I had a made a very ugly function to solve this task. The use of set was reducing the complexity in my code.