考慮以下示例:
string_now = 'apple and avocado'
stringthen = string_now.swap('apple', 'avocado') # stringthen = 'avocado and apple'
&
string_now = 'fffffeeeeeddffee'
stringthen = string_now.swap('fffff', 'eeeee') # stringthen = 'eeeeefffffddffee'
在做法上討論的
一系列replace()方法不僅遠非理想,而且由于順序性質,它不會完美地將事物轉化為
string_now = 'apple and avocado'
stringthen = string_now.replace('apple','avocado').replace('avocado','apple')
給'apple and apple'而不是'avocado and apple'.
那么實作這一目標的最佳方法是什么?
uj5u.com熱心網友回復:
鑒于我們想要交換單詞xand y,并且我們不關心它們重疊的情況,我們可以:
- 在出現以下情況時拆分字串
x - 在每一塊內,替換
y為x - 加入碎片
y
本質上,我們使用字串中的分割點作為臨時標記來避免順序替換的問題。
因此:
def swap_words(s, x, y):
return y.join(part.replace(y, x) for part in s.split(x))
測驗一下:
>>> swap_words('apples and avocados and avocados and apples', 'apples', 'avocados')
'avocados and apples and apples and avocados'
>>>
uj5u.com熱心網友回復:
兩種正則運算式解決方案,另一種適用于確實有無法出現的字符(畢竟有超過一百萬種不同的可能字符)并且不喜歡replace鏈的人:-)
def swap_words_regex1(s, x, y):
return re.sub(re.escape(x) '|' re.escape(y),
lambda m: (x if m[0] == y else y),
s)
def swap_words_regex2(s, x, y):
return re.sub(f'({re.escape(x)})|{re.escape(y)}',
lambda m: x if m[1] is None else y,
s)
def swap_words_replaces(s, x, y):
return s.replace(x, chr(0)).replace(y, x).replace(chr(0), y)
一些基準測驗結果:
3.7 ms 1966 kB swap_words_split
10.7 ms 2121 kB swap_words_regex1
17.8 ms 2121 kB swap_words_regex2
1.3 ms 890 kB swap_words_replaces
完整代碼(在線試用!):
from timeit import repeat
import re
import tracemalloc as tm
def swap_words_split(s, x, y):
return y.join(part.replace(y, x) for part in s.split(x))
def swap_words_regex1(s, x, y):
return re.sub(re.escape(x) '|' re.escape(y),
lambda m: (x if m[0] == y else y),
s)
def swap_words_regex2(s, x, y):
return re.sub(f'({re.escape(x)})|{re.escape(y)}',
lambda m: x if m[1] is None else y,
s)
def swap_words_replaces(s, x, y):
return s.replace(x, chr(0)).replace(y, x).replace(chr(0), y)
funcs = swap_words_split, swap_words_regex1, swap_words_regex2, swap_words_replaces
args = 'apples and avocados and bananas and oranges and ' * 10000, 'apples', 'avocados'
for _ in range(3):
for func in funcs:
t = min(repeat(lambda: func(*args), number=1))
tm.start()
func(*args)
memory = tm.get_traced_memory()[1]
tm.stop()
print(f'{t * 1e3:4.1f} ms {memory // 1000:4} kB {func.__name__}')
print()
uj5u.com熱心網友回復:
我設法使這個功能完全符合您的要求。
def swapwords(mystr, firstword, secondword):
splitstr = mystr.split(" ")
for i in range(len(splitstr)):
if splitstr[i] == firstword:
splitstr[i] = secondword
i =1
if splitstr[i] == secondword:
splitstr[i] = firstword
i =1
newstr = " ".join(splitstr)
return newstr
基本上,它的作用是接收你的 string "Apples and Avacados",并用空格分割它。因此,每個單詞都被索引到一個陣列中splitstr[]。使用這個,我們可以使用 for 回圈來交換單詞。這i =1是為了確保單詞不會被交換兩次。最后,我使用newstr= " ".join(splitstr)which 將字串連接回來,連接由空格分隔的單詞。
運行下面的代碼給我們:
Avacados and Apples.
uj5u.com熱心網友回復:
試試這個功能
def swap_custom(swap, word):
swap_word = word.replace(swap[0], "0")
swap_word = swap_word.replace(swap[1], "1")
swap_word = swap_word.replace("0", swap[1])
swap_word = swap_word.replace("1", swap[0])
return swap_word
string_now = 'apple and avocado'
swap = ['apple', 'avocado']
stringthen = swap_custom(swap, string_now)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373421.html
