在日常使用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('_',''))