Python字符串去除空格有五种常用方法:
1. strip()方法
strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。语法:str.strip([chars])。
# 例 str = " this is string example....wow!!! " print str.strip() # 去除首尾空格 # 输出:this is string example....wow!!!
2. lstrip()方法
lstrip()方法用于截掉字符串左边的空格或指定字符。语法:str.lstrip([chars])。
# 例 str = " this is string example....wow!!! " print str.lstrip() # 去除左边空格 # 输出:this is string example....wow!!!
3. rstrip()方法
rstrip()方法用于删除字符串右边的空格或指定字符。语法:str.rstrip([chars])。
# 例 str = " this is string example....wow!!! " print str.rstrip() # 去除右边空格 # 输出: this is string example....wow!!!
4. replace()方法
replace()方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。语法:str.replace(old, new[, max])。
# 例 str = " this is string example....wow!!! " print str.replace(" ","") # 将字符串中的空格替换为空 # 输出:thisisstringexample....wow!!!
5. join()方法
join()方法用于将序列中的元素以指定的字符连接生成一个新的字符串。语法:str.join(sequence)。
# 例 str = " this is string example....wow!!! " s = str.split() # 将字符串拆分成序列 print "".join(s) # 将序列中的元素以空字符连接 # 输出:thisisstringexample....wow!!!
以上就是,可以根据实际需要选择合适的方法进行处理。