Home > OS >  String Slicing and Compare in Python
String Slicing and Compare in Python

Time:06-20

My target is Slice the string, compare the items and produce the results. Here is my code. But I get the same result for both conditions. The resulting screenshot is attached.

string = ["en_english","enc_english"]
for item in string:
    if item[:2] == "en":
        print("selected item : ",item)
    elif item[:3] == "enc":
        print(item, "is selected")

Result

selected item : en_english
selected item : enc_english

How to get the correct result ?

CodePudding user response:

Both of the strings trigger on the first condition. Try switching the order to check for the more restrictive case first.

string = ["en_english","enc_english"]
for item in string:
    if item[:3] == "enc":
        print(item, "is selected")         
    elif item[:2] == "en":
        print("selected item : ",item)

CodePudding user response:

Maybe it would be easier to use item.split('_')? like:


string = ["en_english","enc_english"]
for item in string:
    prefix = item.split('_')[0]
    if prefix == "en":
        print("selected item : ",item)
    elif prefix == "enc":
        print(item, "is selected")

Only if that is the case you are trying to solve, I just assumed from the question.

  • Related