簡體   English   中英

(Python)拆分字符串多個分隔符更有效? 1) 使用多重替換方法然后使用拆分 2) 使用正則表達式

[英](Python) which is more efficient to split a string multiple separators? 1) Using multiple replace method then using split 2) using regular Expressions

例子:

(情況1)

#首先使用replace方法將不同類型的分隔符替換為單一類型,然后使用split方法

text = "python is, an easy;language; to, learn."
text_one_delimiter = text.replace("# ", ", ").replace("% ", ", ").replace("; ", ", ").replace("- ", ", ")

print(text_one_delimiter.split(", "))

(案例二)

#使用正則表達式進行拆分使用多個分隔符

import re

text = "python is# an% easy;language- to, learn."
print(re.split('; |, |# |% |- ', text))

timeit模塊對於代碼片段的速度比較很有用。 它可以通過以下方式使用:

import timeit
case1 = '''text = "python is, an easy;language; to, learn."
text_one_delimiter = text.replace("# ", ", ").replace("% ", ", ").replace("; ", ", ").replace("- ", ", ")
text_one_delimiter.split(", ")'''
case2_setup = "import re"
case2 = '''text = "python is# an% easy;language- to, learn."
re.split('; |, |# |% |- ', text)'''
print(timeit.timeit(case1))
print(timeit.timeit(case2,case2_setup))

Output(取決於您的機器):

1.1250261999999793
2.2901268999999616

請注意,我從檢查的代碼中排除了printimport re ,否則它會在不需要幾次的情況下導入它。 結論是,在這種特殊情況下,具有多個.replace的方法比re.split更快。

(在 Python 3.7.3 中測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM