簡體   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