I want to check that a string contains only one emoji, using Python 3.
For example, there is a is_emoji
function that checks that the string has only one emoji.
def is_emoji(s):
pass
is_emoji("π") #True
is_emoji("πβΌοΈ") #False
I try to use regular expressions but emojis didn't have fixed length. For example:
print(len("βΌοΈ".encode("utf-8"))) # 6
print(len("π".encode("utf-8"))) # 4
This works in Python 3:
def is_emoji(s):
emojis = "πβΌοΈ" # add more emojis here
count = 0
for emoji in emojis:
count += s.count(emoji)
if count > 1:
return False
return bool(count)
Test:
>>> is_emoji("π")
True
>>> is_emoji('βΌ')
True
>>> is_emoji("πβΌοΈ")
False
Combine with Dunes' answer to avoid typing all emojis:
from emoji import UNICODE_EMOJI
def is_emoji(s):
count = 0
for emoji in UNICODE_EMOJI:
count += s.count(emoji)
if count > 1:
return False
return bool(count)
This is not terrible fast because UNICODE_EMOJI
contains nearly 1330 items, but it works.