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)