简体   繁体   中英

Check if string only contains a certain character in python

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,

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

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.

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