Python字符串去除空格的五种常用方法介绍

分类:知识百科 日期: 点击:0

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!!!

以上就是,可以根据实际需要选择合适的方法进行处理。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。