字符串str去除空格和指定字符的方法总结(Python3)

在日常使用Python的过程中,时常碰到要去除字符串中的空格和指定字符的情况,方法汇总如下:

一、去除字符串左端的空格和指定字符

lstrip()方法可以用来去除指定的字符,用法如下:

str.lstrip([chars])

    a. 去除左端空格

str = '  hello World'

print(str.lstrip())

    b. 去除左端指定字符

str = '#########hello World'

print(str.lstrip('#'))

二、去除字符串右端的空格和指定字符

rstrip()方法可以用来去除指定的字符,用法如下:

str.rstrip([chars])

    a.去除右端空格

str1 = 'hello World   '
print(str1.rstrip())

 b.去除右端指定字符

str1 = 'hello World!#######'
print(str1.rstrip('#'))

三、去除字符串两端的空格和指定字符

rstrip()方法可以用来去除指定的字符,用法如下:

str.strip([chars])

    a.去除两端空格

str1 = '  hello World!   '
print(str1.strip())

    b.去除两端指定字符

str1 = '###hello World!#####'
print(str1.strip('#'))

四、利用replace() 方法去除字符串中的空格

replace()方法用来替换字符串中的指定字符串,并可以指定最大替换次数。

语法如下:

str.replace(old, new[, max])

用这个思路可以用来去除空格:

str = '  this is a string  '
print(str.replace(' ',''))

去除指定字符:

str = '___this_is_a_string________'
print(str.replace('_',''))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值