For this problem, I want to search through the tuple and find all states that start with 'N' and insert it to a new list.
I attempted the problem and got stuck. Can anyone help me out? Thank you
states = ("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY")
letterN = "N"
listN=[]
for i in states:
if i == letterN:
listN.append(i)
CodePudding user response:
listN=[st for st in states if st.startswith('N')]
> output: ['NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND']
CodePudding user response:
If you want a function instead of a script:
def find_n_states(states, letter):
n_states = []
for state in states:
if state[0] == letter:
n_states.append(state)
return n_states
find_n_states(states, 'N')
Output: ['NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND']
CodePudding user response:
The problem is that you are saying if i == letterN which would always return to false since "N-" does not equal "N". We can use str.startswith(substring) to check if the string starts with the given substring.
states = ("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY")
letterN = "N"
listN=[]
for i in states:
if i.startswith(letterN):
listN.append(i)