Reputation: 21
For the character F
only:
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []
for word in sportslist:
if word.startswith('F'):
newl.append(word)
print (newl)
Output:
['Football'] , ['Fencing']
I used the for
loop to obviously repeat the coding but for some reason when I try print out multiple words beginning with another letter, say I wanted to print out the words beginning with F
and B
. How would I execute that as I just get a blank output?
Upvotes: 1
Views: 93
Reputation: 49
If you want to get fancy and complicate things, then you can use the filter
function:
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
letters = ('F', 'B')
new1 = list(filter(lambda item:item.startswith(letters), sportslist))
print(new1)
#['Football', 'Fencing', 'Basketball', 'Baseball'] # <-- output
Upvotes: 0
Reputation: 14131
You may use
a tuple of all accepted starting strings (as an argument of the .startswith()
method),
(eventually) a list comprehension
(instead of your for
loop with the if
statement and the .append()
method):
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = [word for word in sportslist if word.startswith(("F", "B"))]
print(newl)
['Football', 'Fencing', 'Basketball', 'Baseball']
Note:
I added superfluous spaces into the list comprehension to emphasize its 3 parts:
word
- what to add into the target list,for word in sportslist
— from where is word
in the point 1. iteratively obtained,if word.startswith(("F", "B"))
- which condition must word
from the point 2. satisfy.Upvotes: 2
Reputation: 14131
You may use a tuple ('F', 'B')
as an argument of the .startswith()
method and correct the indentation of the last line of your code:
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []
for word in sportslist:
if word.startswith(('F', 'B')):
newl.append(word)
print (newl) # <------------ no indentation!
Upvotes: 0
Reputation: 71570
You could do an or
and apply another startswith
for B
, that would work:
for word in eustates:
if word.startswith('F') or word.startswith('B'):
newl.append(word)
print (newl)
Or you could try:
for word in eustates:
if word[:1] in 'BF':
newl.append(word)
print (newl)
Or:
for word in eustates:
if 'BF'.__contains__(word[:1]):
newl.append(word)
print (newl)
Upvotes: 1