簡體   English   中英

從 python 中的字符串中刪除任何類型的引號

[英]Remove any kind of quotes from a string in python

示例字符串:

'" "Hello World" "'
'" Today isn't a good day for hello world"'
'" Today "is" a good day for hello world "'

Output:

'"Hello World'"
'"Today isnt a good day for hello world'"
'"Today is a good day for hello world'"

我嘗試了字符串替換,但我無法執行str.replace("\"'", "") 。是否有使用正則表達式甚至簡單替換方法的好方法?

您可以調用 replace 兩次。

你可以使用 str.translate:

>>> s = '" "Hello World" "'
>>> remove_quotes = str.maketrans('', '', "'\"")
>>> s.translate(remove_quotes)
' Hello World '

您可以使用正則表達式。

這些方法中的任何一種都會起作用。

使用str.translate一次執行兩個替換。

quote_dropper = str.maketrans('', '', '\'"')  # Ideally done once up front, and reused

# ... later, when you need to strip quotes from a string ...
mystr = mystr.translate(quote_dropper)

str.maketrans只是制作了一個簡單的dict ,將兩個字符的代碼映射到None ,這就是您告訴translate在遇到時刪除所述字符的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM