一、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/zh-tw/n/157309.html