在python中刪除字符串中的特定字符,在python中,字符串是不變的,這意味著一旦創建,就無法更改其內容。要修改字符串,您需要將其重新命名為帶有所需更改的新字符串。
使用str.translate
,您可以使用str.translate方法從字符串中刪除特定字符。 This method allows you to specify a translation table, which maps characters to be replaced.line = line.translate(None, "!@#$") # Remove all occurrences of "!@#$"Using re.subline = "Hello world!" line = line.replace("!", "") # Replace all occurrences of "!" with an empty stringThe re.sub method performs regular expression substitution on a string.您可以使用它來刪除字符類中的字符。
在python 3中,字符串是Unicode,是Unicode,它需要用於移除字符的不同方法。您需要通過映射Unicode代碼指向none的翻譯字典,而不是將其作為第二個參數。 line = line.translate(translation_table)
替代方法line = line.translate(None, "!@#$") # Remove all occurrences of "!@#$"
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3