how can I check i only have l/r/u/d/x/y/z/w in a string? (python)

I have a string

I want to check it contains only l/r/u/d/x/y/z/w

but I can't think of a short code to do so

Glad for your help

Thanks

4 answers

  • answered 2021-07-27 17:37 Thierry Lathuille

    Just use sets and check if the set of letters in your sentence is a subset of all your letters:

    set(mystring).issubset("lrudxyzw")
    

    Note that the argument to subset doesn't have to be a set, any iterable is accepted.

  • answered 2021-07-27 17:39 Hristo Boyadzhiev

    A bit clearer than Thierry's answer:

    all(char in "lrudxyzw" for char in mystring)
    

  • answered 2021-07-27 17:57 Robert Cotterman

    Regex Variant

    import re
    string="xyz"
    if re.match('^[lrudxyzw]*$', string):
        do code
    

    Could also use

    if re.fullmatch('[lrudxyzw]*', string):
        do code
    

  • answered 2021-07-27 18:02 Kelly Bundy

    not mystring.strip('lrudxyzw')
    

    That checks whether stripping the good letters doesn't leave anything behind.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum