简体   繁体   中英

How do I compare two strings using a for loop?

I'm building a simple email verifier. I need to compare the local-parts current letter to a list of valid characters. So essentially I'm asking how do I check to see if the current letter I'm on in local-part is equivalent to a letter in the ENTIRE list of valid chars. If it is a valid character, local-part will go to the next letter in its string and go through the list of valid characters to see if this too is and so on until it reaches the @ symbol unless there isn't a valid character.

I'm fairly new to python so I don't know how nested for loops work.

for ch in local:
    for ch in valChar:
    if(ch ==ch) <----problem

This is what I currently have written for the loops. Is "ch" a variable or some type of syntax to represent char?

You don't need nested loop in this case, thanks to the in operator:

for c in local:
    if c in valChar:
        performvalidaction(c)
    else:
        denoteasinvalid(c)

What identifier to use ( c , ch , or anything else) is pretty indifferent, I tend to use single-character identifiers for loop variables, but there's no rule saying that you must.

If you did have to use two nested loops, you'd just use different loop variables for the two loops.

In fact you don't even need one loop here (you could instead work eg with Python's set s, for example) -- much less two -- but I guess using one loop is OK if it's clearer for you.

ch is a variable, you can replace it with any valid identifier:

for local_ch in local:
    for valChar_ch in valChar:
        if(local_ch == valChar_ch): <----No problem

Let me explain the for loop for you:

for eachitem in file:
    do something

eachitem is a variable of one specific value of a file/dictionairy etc..

您需要验证一个电子邮件地址,我将使用正则表达式:\\ b [A-Z0-9 ._%+-] + @ [A-Z0-9 .-] +。[AZ] {2,6} \\ b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM