一、strip()方法的使用
strip()方法是Python中常用的字符串方法,它用于去掉字符串首尾的指定字符,默认为去除空格字符。
示例代码:
str1 = " hello world "
print(str1.strip()) # 输出"hello world"
print(str1.strip(" ")) # 输出"hello world"
print(str1.strip(" h")) # 输出"ello world"strip()方法可以接收一个参数,表示要去除的字符。如果字符串中包含多个连续出现的指定字符,则只会去除首尾的。
二、去除空格的方法
除了使用strip()方法去除空格外,还可以使用其他方法实现。
1. replace()方法
replace()方法可以将一个字符替换为另一个字符,通过将空格替换为空字符串来去除字符串中的空格。
示例代码:
str1 = " hello world "
print(str1.replace(" ", "")) # 输出"helloworld"2. split()方法
split()方法可以将字符串按指定字符分割成列表,通过将字符串按空格分割再用join()方法拼接列表的元素来去除空格。
示例代码:
str1 = " hello world "
print("".join(str1.split())) # 输出"helloworld"3. 正则表达式
利用正则表达式模块re,通过re.sub()方法将字符串中的空格替换为空字符串。
示例代码:
import re
str1 = " hello world "
print(re.sub(r"\s+", "", str1)) # 输出"helloworld"三、多种方法的性能差异
在Python中,有多种方法可以去除字符串中的空格,但它们的性能并不相同。下面利用timeit模块比较不同方法的性能。
示例代码:
import timeit
# strip()方法
print(timeit.timeit('str1=" hello world "; str1.strip()', number=1000000))
# replace()方法
print(timeit.timeit('str1=" hello world "; str1.replace(" ", "")', number=1000000))
# split()方法
print(timeit.timeit('str1=" hello world "; "".join(str1.split())', number=1000000))
# 正则表达式方法
import re
print(timeit.timeit('str1=" hello world "; re.sub(r"\s+", "", str1)', number=1000000))测试结果表明,strip()方法是去除空格最快的方法。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/157309.html
微信扫一扫
支付宝扫一扫