Emma Conlon
Emma Conlon

Reputation: 21

how to check if a string in python contains a random set of characters from another string

i have a source word as a string and i have a string where people input a list of words but how do i check too see of the inputted string only contains characters from the sourceword but in any order

def check(input_string):
    import re
    #http://docs.python.org/library/re.html
    #re.search returns None if no position in the string matches the pattern
    #pattern to search for any character other then . a-z 0-9
    pattern =word
    if re.search(pattern, test_str):
        #Character other then . a-z 0-9 was found
        print('Invalid : %r' % (input_string,))
    else:
        #No character other then . a-z 0-9 was found
        print('Valid   : %r' % (input_string,))```

Upvotes: 1

Views: 112

Answers (2)

Nukala Raghava Aditya
Nukala Raghava Aditya

Reputation: 45

def fun():

s = "Test" # Word
b = "TEST" #input_string
a = True
for c in b:
    if c.lower() not in s.lower():
        a = False
        break
if (a == False):
    print("Character is not in s")
else:
    print("No Other characters found")

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114330

Use set, which supports checking for subset.

template = set(word)
if set(input_string) < template:
    print("OK")

If you insist on using regex, turn the template into a character class:

template = re.compile(f'[{word}]+')
if template.fullmatch(input_string):
    print("OK")

Upvotes: 4

Related Questions