Home > database >  I want to find string in a list that start with ‘A’ in python
I want to find string in a list that start with ‘A’ in python

Time:07-02

I tried

List1=[]
for i in name:
If i.startwith(‘A’)
List1.append(i)
Print(List1)

How can i find strings that start with ‘A’ in a list and print it but using slicing and not startwith()

CodePudding user response:

sample with your own code whithout startswith():

List1=[]
name=["Amilad","Ahmad","kirKark"]
for i in name:
    if i[0]=='A':
        List1.append(i)
print(List1)

output:

['Amilad', 'Ahmad']

CodePudding user response:

Using slicing:

name = ['Adil','Robert'] #list with names
List1=[]
for i in name:
    if i[:1] == 'A':
        List1.append(i)
print(List1)

Output:

['Adil']

CodePudding user response:

name = ["Belgium", "Antwerp", "France"]

List1=[]
for i in name:
    if i[0] == "A":
        List1.append(i)
print(List1)

CodePudding user response:

A list comprehension with a condition based on a slice might work for you. For example:

names = ['Arthur', 'Brian', 'Anthony', '', 'Banana', 'Antirrhinum']

new_list = [name for name in names if name[:1] == 'A']

print(new_list)

Output:

['Arthur', 'Anthony', 'Antirrhinum']
  • Related