[英]How do I insert a string into a specific section of a larger string?
我正在嘗試編寫一個自動生成多個 URL 的小程序,每個 URL 基本相同,唯一的區別是在每個 URL 中插入了不同的外語縮寫。
例如,我有這個代碼:
base_url = 'https://habitica.fandom.com/wiki/Special:WhatLinksHere'
wiki_page = '/File:Gold.png'
languages = ['da', 'de', 'es', 'fr', 'it', 'ja', 'nl', 'pl', 'pt-br', 'ru', 'tr', 'zh']
所以我想在“wiki”之前的地方將這些語言縮寫中的每一個插入到 base_url 值中,導致
https://habitica.fandom.com/da/wiki/Special:WhatLinksHere
https://habitica.fandom.com/de/wiki/Special:WhatLinksHere
https://habitica.fandom.com/es/wiki/Special:WhatLinksHere
等等。
我該怎么做呢? 是否有一種相當通用的方法,或者我是否需要了解有關字符串特定文本的一些非常詳細的代碼?
謝謝! 約翰
你可以制作一個模板str
並將其format
,
>>> languages
['da', 'de', 'es', 'fr', 'it', 'ja', 'nl', 'pl', 'pt-br', 'ru', 'tr', 'zh']
>>> template = 'https://habitica.fandom.com/{}/wiki/Special:WhatLinksHere'
>>> urls = []
>>> for lang in languages:
... urls.append(template.format(lang))
...
>>> print('\n'.join(urls))
https://habitica.fandom.com/da/wiki/Special:WhatLinksHere
https://habitica.fandom.com/de/wiki/Special:WhatLinksHere
https://habitica.fandom.com/es/wiki/Special:WhatLinksHere
https://habitica.fandom.com/fr/wiki/Special:WhatLinksHere
https://habitica.fandom.com/it/wiki/Special:WhatLinksHere
https://habitica.fandom.com/ja/wiki/Special:WhatLinksHere
https://habitica.fandom.com/nl/wiki/Special:WhatLinksHere
https://habitica.fandom.com/pl/wiki/Special:WhatLinksHere
https://habitica.fandom.com/pt-br/wiki/Special:WhatLinksHere
https://habitica.fandom.com/ru/wiki/Special:WhatLinksHere
https://habitica.fandom.com/tr/wiki/Special:WhatLinksHere
https://habitica.fandom.com/zh/wiki/Special:WhatLinksHere
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.