简体   繁体   中英

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. 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:

thestring = ["ab"]

(And then add the if statement ^^) It wouldn't work anymore. 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"). That one element is not equal to the string "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.

Just put variable.isSomethingHere to see.

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

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