Home > other >  Check if string only contains a certain character in python
Check if string only contains a certain character in python

Time:07-16

How would I go about checking if a string only contains a certain character?

string_to_check = "aaaaaa"
character = "a"

I have tried

elif " " in cmd:
     return print(Fore.RED   f"Input cannot be nothing.")

But this applies to strings with the character in it, I would like to apply string with only the character in it... For example

does_contain_only("a", "aaaaaa") # True
does_contain_only("a", "aaaaba") # False

Although I don't know any commands / functions to do this,

CodePudding user response:

You could check if a string only contains a certain character, like this:

def does_contain_only(char, string):
    return all([c == char for c in string])
print(does_contain_only("a", "aaaaa")) # True
print(does_contain_only("a", "aaaba")) # False

CodePudding user response:

One short solution:

set(string_to_check) == {'a'}

# Or, as a function:
def does_contain_only(character, target):
    return set(target) == { character }

You don't specify whether checking the empty string should return True or False. It is certainly the case that every character in an empty string is 'a'. Every character is also 'b'. These are both the case because there are no characters in the empty string, so "every character is X" is trivially true for any predicate X (even if X cannot be True for any character).

Sometimes that's what you want and sometimes it isn't. My solution above returns False for the empty string, while the possibly more obvious all(ch == character for ch in target) would return True.

  • Related