简体   繁体   English

如何使用for循环比较两个字符串?

[英]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. 如果它是有效字符,则local-part将转到其字符串中的下一个字母,并通过有效字符列表来查看是否也是如此,依此类推,直到到达@符号为止,除非没有有效字符。

I'm fairly new to python so I don't know how nested for loops work. 我是python的新手,所以我不知道嵌套的循环如何工作。

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? “ ch”是变量还是某种表示char的语法?

You don't need nested loop in this case, thanks to the in operator: 在这种情况下,由于in运算符,您不需要嵌套循环:

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. 使用什么标识符( cch或其他任何东西)都没什么大不了,我倾向于将单字符标识符用于循环变量,但是没有规则说必须这样做。

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. 实际上,您甚至在这里甚至不需要一个循环(例如,您可以使用Python的set s进行工作)-少得多两个-但我想如果您更清楚使用一个循环就可以了。

ch is a variable, you can replace it with any valid identifier: ch是一个变量,您可以将其替换为任何有效的标识符:

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循环:

for eachitem in file:
    do something

eachitem is a variable of one specific value of a file/dictionairy etc.. eachitem是文件/字典等的一个特定值的变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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