[英]Add a single backslash (“\”) to string in python
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:我需要在第一个字母 U 前添加“\”,这样 output 将如下所示:
["\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?如何在每个字符串前面只添加一个反斜杠?
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"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.