要去掉Python字符串(str)内部的空格,您可以使用replace()方法或者正则表达式来删除空格
要去掉Python字符串(str)内部的空格,您可以使用replace()
方法或者正则表达式来删除空格。以下是两种方法的示例:
1、使用replace()
方法:
original_string="HelloWorld" new_string=original_string.replace("","") print(new_string)
这将输出:HelloWorld
,其中所有空格都被删除。
2、使用正则表达式:
importre original_string="HelloWorld" new_string=re.sub(r'\s+','',original_string) print(new_string)
这段代码使用正则表达式\s+
来匹配一个或多个空格,并用空字符串替换它们。最终输出为:HelloWorld
,即不包含任何空格的字符串。
版权声明
本文仅代表作者观点,不代表博信信息网立场。