How can i return the second element in the list that starts with “b”

后端 未结 4 765
误落风尘
误落风尘 2021-01-25 18:09

I have this function with lists that has strings in it and I have to find the second element in this list that starts with \"b\".

for example:

second_e         


        
4条回答
  •  野的像风
    2021-01-25 19:01

    You can use the python built-in function startswith() to check the first element of the string.

    lst = ["b", "a", "bb"]
    
    # Check the first element
    sample = "Sample"
    print(sample.startswith("S"))
    # Output : True
    

    Now, you need to iterate through list to check each of the indices that starts with b

    # Create empty list
    lst_2 = []
    # Loop through list
    for element in lst.startswith("b"):
        # Add every element starts with b
        lst_2.append(element)
        # Print the second element which starts with b
        print(lst_2[1])
    

提交回复
热议问题