Loop string and stop when invalid charater

Hello all…i have string → TTBBKKM90A**%$01.
I want to make a python script that loop that string and stop when invalid character.
So the result/output will be → TTBBKKM90A
I made the code

x = "TTBBKKM90A**%$01."
kkk = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.";
for element in x:
    if element in kkk:
        print(element, end="")
        
print(element)

But output is TTBBKKM90A01… I am expecting TTBBKKM90A

Hope someone can help…thanks

You’re better off using regular expressions for this:

x = re.match(r"\w+", x).group(0)

1 Like

Add a break to make it stop looping:

for element in x:
    if element not in kkk:
        break

    print(element, end="")
1 Like

Thanks to BOTH of you…your solution works…keep safe guys")

1 Like