給定帶有標記( * )的輸入( http 引數)到工具,我想用字串替換標記,但一次只有一個標記
編碼:
....
inp = input("http params:" ) # aa=bb*&cc=dd*&ee=ff*
attributes = ["AA","BB","CC"]
mark = "*"
for mark in inp:
for attribute in attributes:
data = inp.replace("*", ")(" attribute)
print(data)
....
我有這個輸出:
aa=bb)(AA&cc=dd)(AA&ee=ff)(AA
aa=bb)(BB&cc=dd)(BB&ee=ff)(BB
aa=bb)(CC&cc=dd)(CC&ee=ff)(CC
[..]
雖然我想要這個:
aa=bb)(AA&cc=dd&ee=ff
aa=bb)(BB&cc=dd&ee=ff
aa=bb)(CC&cc=dd&ee=ff
aa=bb&cc=dd)(AA&ee=ff
aa=bb&cc=dd)(BB&ee=ff
aa=bb&cc=dd)(CC&ee=ff
aa=bb&cc=dd&ee=ff)(AA
aa=bb&cc=dd&ee=ff)(BB
aa=bb&cc=dd&ee=ff)(CC
uj5u.com熱心網友回復:
在這里,我們將需要一些函式來替換特定數量*而不是全部替換。此外,我從這里nth_repl參考了以下樂趣。
代碼:
def nth_repl(s, sub, repl, n):
find = s.find(sub)
# If find is not -1 we have found at least one match for the substring
i = find != -1
# loop util we find the nth or we find no match
while find != -1 and i != n:
# find 1 means we start searching from after the last match
find = s.find(sub, find 1)
i = 1
# If i is equal to n we found nth match so replace
if i == n:
return s[:find] repl s[find len(sub):]
return s
inp = input("http params:" ) # aa=bb*&cc=dd*&ee=ff*
attributes = ["AA","BB","CC"]
for n in range(1, inp.count('*') 1):
for attribute in attributes:
data = nth_repl(inp, "*", f')({attribute}',n)
print(data)
或者沒有函式:
for i, v in enumerate(inp):
for attribute in attributes:
if '*' in v:
print(inp[:i] f')({attribute}' inp[i 1:])
輸出:
http params:aa=bb*&cc=dd*&ee=ff*
aa=bb)(AA&cc=dd*&ee=ff*
aa=bb)(BB&cc=dd*&ee=ff*
aa=bb)(CC&cc=dd*&ee=ff*
aa=bb*&cc=dd)(AA&ee=ff*
aa=bb*&cc=dd)(BB&ee=ff*
aa=bb*&cc=dd)(CC&ee=ff*
aa=bb*&cc=dd*&ee=ff)(AA
aa=bb*&cc=dd*&ee=ff)(BB
aa=bb*&cc=dd*&ee=ff)(CC
uj5u.com熱心網友回復:
這似乎是正則運算式的一個很好的用例,所以:
>>> import re
>>> inp = 'aa=bb*&cc=dd*&ee=ff*'
>>> attributes = ["AA","BB","CC"]
>>> for match in re.finditer(r"\*", inp):
... for attr in attributes:
... left_part = inp[: match.start()]
... right_part = inp[match.end() :]
... result = f"{left_part})({attr}{right_part}"
... print(result)
...
aa=bb)(AA&cc=dd*&ee=ff*
aa=bb)(BB&cc=dd*&ee=ff*
aa=bb)(CC&cc=dd*&ee=ff*
aa=bb*&cc=dd)(AA&ee=ff*
aa=bb*&cc=dd)(BB&ee=ff*
aa=bb*&cc=dd)(CC&ee=ff*
aa=bb*&cc=dd*&ee=ff)(AA
aa=bb*&cc=dd*&ee=ff)(BB
aa=bb*&cc=dd*&ee=ff)(CC
>>>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518012.html
上一篇:熊貓以不同的間隔劃分時間
