python中如何删除中间空格_Python如何删除字符串中所有空格

在Python中删除字符串中所有空格有:使用replace()函数、使用split()函数+join()函数、使用Python正则表达式。下面本篇文章就来具体介绍一下这些方法,希望对大家有所帮助。【相关视频教程推荐:Python教程】

使用replace()函数

我们可以使用replace()函数,把所有的空格(" ")替换为("")def remove(string):

return string.replace(" ", "");

string = ' H E L L O ! ';

print("原字符串:"+string) ;

print("\n新字符串:"+remove(string)) ;

输出:

使用split()函数+join()函数

split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。def remove(string):

return "".join(string.split());

string = 'w o r l d ';

print("原字符串:"+string) ;

print("\n新字符串:"+remove(string)) ;

输出:

使用Python正则表达式

Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。

re 模块使 Python 语言拥有全部的正则表达式功能。#导入re 模块

import re

def remove(string):

pattern = re.compile(r'\s+');

return re.sub(pattern,'', string);

string = 'P y t h o n';

print("原字符串:"+string);

print("\n新字符串:"+remove(string)) ;

输出:

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注Gxl网相关教程栏目!!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值