1、replace()方法,可以去除全部空格
语法
str.replace(old, new[, max])
- old – 将被替换的子字符串。
- new – 新字符串,用于替换old子字符串。
- max – 可选字符串, 替换不超过 max 次
实例
str = "this is string example....wow!!! this is really string";
print(str.replace(" ", ""))
#输出 thisisstringexample....wow!!!thisisreallystring
2、strip()方法,去除字符串开头或者结尾的空格
语法
str.strip([chars]);
- chars – 移除字符串头尾指定的字符序列。
实例
str = "00000003210Runoob01230000000";
print(str.strip('0')) # 去除首尾字符 0
str2 = " Runoob " # 去除首尾空格
print(str2.strip())
#输出:
#3210Runoob0123
#Runoob
3、rstrip()方法,去除字符串结尾的空格
语法
str.rstrip([chars])
参数
- chars – 指定删除的字符(默认为空格)
返回值
返回删除 string 字符串末尾的指定字符后生成的新字符串。
实例
str = " this is string example....aaaaa!!! "
print (str.rstrip())
str = "#######this is string example....aaaaa!!!######"
print (str.rstrip('#'))
#输出:
# this is string example....aaaaa!!!
#######this is string example....aaaaa!!!
4、lstrip()方法,去除字符串开头的空格;
语法
str.lstrip([chars])
参数
- chars --指定截取的字符。
返回值
返回截掉字符串左边的空格或指定字符后生成的新字符串。
实例
str = " this is string example!!! "
print( str.lstrip() )
str = "#########this is string example!!!#########"
print( str.lstrip('#') )
# 输出
# this is string example!!!
# this is string example!!!#########
5、join()方法+split()方法,可以去除全部空格;
语法
str.join(sequence)