在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