繁体   English   中英

在 python 中的字符串中添加一个反斜杠 (“\”)

[英]Add a single backslash (“\”) to string in python

我有一个字符串数组,如下所示:

["U0001f308", "U0001F602"]

我需要在第一个字母 U 前添加“\”,这样 output 将如下所示:

["\U0001f308", "\U0001F602"]

这是我到目前为止尝试过的代码:

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

如何在每个字符串前面只添加一个反斜杠?

我猜你想要的是以下代码:

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

哪个打印

['🌈', '😂']

这与我们执行以下代码时的结果相同:

print(["\U0001f308", "\U0001F602"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM