1

I have an array of strings which looks like:

["U0001f308", "U0001F602"]

I need to add “\” in front of the first letter U so the output will be like:

["\U0001f308", "\U0001F602"]

This is the code I have tried so far:

matches = ["U0001f308", "U0001F602"]
emojis = [emoji.replace('U', r"\U") for emoji in matches]
print(emojis) #this prints ['\\U0001f308', '\\U0001F602'] which has two blacklashes

How can i add only one backslash in front of every string?

S3DEV
  • 8,768
  • 3
  • 31
  • 42
TRomesh
  • 4,323
  • 8
  • 44
  • 74
  • It does have only one backslash. When you print a list it calls `repr` on its members which prints the backslash as a double backslash. – Roy Avidan Aug 02 '20 at 09:41
  • 1
    Does this answer your question? [Difference between \_\_str\_\_ and \_\_repr\_\_?](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr) – Roy Avidan Aug 02 '20 at 09:43
  • It looks like you're actually trying to create a single unicode character, not a string with the characters backslash, 'U', '0', etc. Is this correct? – interjay Aug 02 '20 at 09:45
  • I tried to use chr(92) and merge it into the array but it prints double \\. – Pooya Panahandeh Aug 02 '20 at 09:51
  • Does this answer your question? [How to properly print list of unicode characters in python?](https://stackoverflow.com/questions/47263783/how-to-properly-print-list-of-unicode-characters-in-python) – Gino Mempin Aug 02 '20 at 11:21

1 Answers1

3

I guess what you want is the following code:

matches = ["U0001f308", "U0001F602"]
emojis = [emoji.replace('U', r"\U").encode().decode('unicode-escape') for emoji in matches]
print(emojis)

which prints

['', '']

It's the same result as when we execute the following code:

print(["\U0001f308", "\U0001F602"])
Gorisanson
  • 2,202
  • 1
  • 9
  • 25