給定一個字串,如:
strng = 'http://example.com/example/xyz?abc1234'
我想替換最后一個“/”和“?”之間的所有內容,即用串列中的元素替換“xyz”部分,例如:
lst = ['apple', 'banana', 'carrot']
這樣我就可以這樣做:
for element in list:
print(strng)
它回傳
http://example.com/example/apple?abc1234
http://example.com/example/banana?abc1234
http://example.com/example/carrot?abc1234
uj5u.com熱心網友回復:
您可以"xyz"用占位符替換并使用str.format:
strng = strng.replace('/xyz?', '/{}?')
for item in lst:
print(strng.format(item))
輸出:
http://example.com/example/apple?abc1234
http://example.com/example/banana?abc1234
http://example.com/example/carrot?abc1234
uj5u.com熱心網友回復:
strng = 'http://example.com/example/xyz?abc1234'
lst = ['apple', 'banana', 'carrot']
for item in lst:
newstring = strng.replace('xyz',item)
print (newstring)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433687.html
