使用replace()函数
我们可以使用replace()函数,把所有的空格(" ")替换为("")
def remove(string):
return string.replace(" ", "");
string = ' H E L L O ! ';
print("原字符串:"+string) ;
print("
新字符串:"+remove(string)) ;输出:
使用split()函数+join()函数
split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。
def remove(string):
return "".join(string.split());
string = 'w o r l d ';
print("原字符串:"+string) ;
print("
新字符串:"+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("
新字符串:"+remove(string)) ;输出:
Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务