Find strings in a list that between specific ascii values – Python

I am trying to find certain string in a list that are between a lowerbound and upperbound (these are user input values). For example say I have a list, states = [‘OH’, ‘NJ’, ‘NY’, ‘SD’, ‘NH’, ‘WI’]. The user inputs lowerbound = ‘NJ’ and upperbound = ‘SD’. I want the code to output [‘OH’, ‘NJ’, ‘NY’, ‘SD’].

What I thought I could do is to separate each string into its own individual characters.

So for the user inputs I wrote this so that the ascii values of the input are added. Each character is added from the input in this case.

a = ord(lowerbound[0].lower()) + ord(lowerbound[1].lower())
b = ord(upperbound[0].lower()) + ord(upperbound[1].lower())

So then I tried this to retrieve the elements in a list that are between the user input. First it coverts all the elements in the list to their added ascii value. But it is not giving me the output I desire.

s_lst = []
lst = []
for s in states:
    x = ord(s[0].lower()) + ord(s[1].lower())
    lst.append(x)
    for i in lst:
        if (b >= i >= a):
            s_lst.append(i)
print(s_lst)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use a list comprehension to filter the list:

states = ['OH', 'NJ', 'NY', 'SD', 'NH', 'WI']

lowerbound = 'NJ'
upperbound = 'SD'

>>> [state for state in states if lowerbound<=state<=upperbound]
['OH', 'NJ', 'NY', 'SD']


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x