[英]How to add a character after and before in string in Python?
I have two variable, one is string and other is list. 我有两个变量,一个是字符串,另一个是列表。
string_val = 'CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{\"subscriptionId\":\"//blp/mktdata/BLOOMBERG IDENTIFIER?fields=LAST_PRICE\",\"MarketDataEvents\":{\"LAST_PRICE\":50.84}}"}'
list_val = ["25746UCY3 Corp","BBG00JM9XLN6 Equity","CFM0987JKM Pro"]
In desired output, u can observe instead of 'BLOOMBERG IDENTIFIER', element of list_val is inserted. 在所需的输出中,您可以观察到插入了list_val元素而不是“ BLOOMBERG IDENTIFIER”。 I have tried below code, but not get successful. 我尝试了下面的代码,但没有成功。
for i in range(0,len(list_val)):
print(len(list_val))
expect_val = string_val.split('mktdata/',0)[1] + list_val[i] + string_val.split('?fields',0)[-1]
print(expect_val)
Desired output: 所需的输出:
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{\"subscriptionId\":\"//blp/mktdata/25746UCY3 Corp?fields=LAST_PRICE\",\"MarketDataEvents\":{\"LAST_PRICE\":50.84}}"}
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{\"subscriptionId\":\"//blp/mktdata/BBG00JM9XLN6 Equity?fields=LAST_PRICE\",\"MarketDataEvents\":{\"LAST_PRICE\":50.84}}"}
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{\"subscriptionId\":\"//blp/mktdata/CFM0987JKM Pro?fields=LAST_PRICE\",\"MarketDataEvents\":{\"LAST_PRICE\":50.84}}"}
Please suggest, how can I achieve this? 请提出建议,我该如何实现?
You can just use .replace(x, y)
: 您可以只使用.replace(x, y)
:
string_val = 'CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{\"subscriptionId\":\"//blp/mktdata/BLOOMBERG IDENTIFIER?fields=LAST_PRICE\",\"MarketDataEvents\":{\"LAST_PRICE\":50.84}}"}'
list_val = ["25746UCY3 Corp","BBG00JM9XLN6 Equity","CFM0987JKM Pro"]
for x in list_val:
print(string_val.replace('BLOOMBERG IDENTIFIER', x))
Output: 输出:
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{"subscriptionId":"//blp/mktdata/25746UCY3 Corp?fields=LAST_PRICE","MarketDataEvents":{"LAST_PRICE":50.84}}"}
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{"subscriptionId":"//blp/mktdata/BBG00JM9XLN6 Equity?fields=LAST_PRICE","MarketDataEvents":{"LAST_PRICE":50.84}}"}
CreateTime:1557770979668 {"schema":{"type":"string","optional":false},"payload":"{"subscriptionId":"//blp/mktdata/CFM0987JKM Pro?fields=LAST_PRICE","MarketDataEvents":{"LAST_PRICE":50.84}}"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.