简体   繁体   English

您将如何检查字母/数字/符号是否在字符串中? (Python)

[英]How would you check if a letter/number/symbol is in a string? (Python)

Sorry for asking a fairly simple question, but how would I make it so that if a certain letter/symbol/number would "activate" an if statement when the letter (for example "a") is in the element.很抱歉问了一个相当简单的问题,但是我将如何做到这一点,以便当某个字母(例如“a”)在元素中时某个字母/符号/数字会“激活”if语句。 If I make如果我做

thestring = ["a"]

(And then add the if statement ^^) Then it would work but if I add another letter or number next to it: (然后添加 if 语句 ^^)然后它会起作用,但是如果我在它旁边添加另一个字母或数字:

thestring = ["ab"]

(And then add the if statement ^^) It wouldn't work anymore. (然后添加 if 语句 ^^)它不再起作用了。 So essentially, how can I fix this?所以基本上,我该如何解决这个问题?

Sample Code:示例代码:

thestring = ["fvrbgea"]

if "a" in thestring:
  print("True")
Output: (Nothing here since there's not an else code I guess.)

As Klaus D. alluded to, your string is a list of one element ("fvrbgea").正如 Klaus D. 所暗示的,您的字符串是一个包含一个元素的列表(“fvrbgea”)。 That one element is not equal to the string "a".那个元素不等于字符串“a”。 If you remove the brackets from thestring your code will execute the way you are expecting to.如果您从字符串中删除括号,您的代码将按照您期望的方式执行。

if you want to just validate if a string contains letters/numbers/symbols you should use regex:如果您只想验证字符串是否包含字母/数字/符号,您应该使用正则表达式:

import re

string = "mystring"

#Validate numbers, lowercase letters, dashes
if re.match("^[0-9a-z-]+$", string):
    print("True.")
else:
    print("False.")
thestring = ["fvrbgea"]
for el in thestring:
    if el.isnumeric():
        print("Numeric")
    elif el.isalnum():
        print("AlNum")
    # elif el.isPutSomethingHere

The python basic library have the "is" method to check the string. python基本库有“is”方法来检查字符串。

Just put variable.isSomethingHere to see.直接把 variable.isSomething 放在这里看看。

Example例子

And if you want to check if a specify letter is in the string, just follow the same logic, and in certain cases you will ned put another for in the initial loop如果你想检查一个指定的字母是否在字符串中,只需遵循相同的逻辑,在某些情况下你会在初始循环中放置另一个

thestring = ["fvrbdoggea"]
control = list()
for el in thestring:
    for c in el:
        if "".join(control) != "dog":
            if c == "d" or c == "o" or c == "g":
                control.append(c)
print("".join(control))

you can automatize that, but, it's a bit hardeful and i don't wanna do, but with this you can take an idea你可以自动化,但是,这有点难,我不想这样做,但是有了这个,你可以想个主意

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

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