如何将字符串插入较大字符串的特定部分?

问题描述 投票:0回答:1

[我正在尝试编写一个小程序,该程序自动生成许多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

依此类推。

我应该如何去做?有没有一种比较通用的方法,或者我需要进入一些有关字符串的特定文本的非常详细的代码吗?

谢谢!约翰

python string
1个回答
1
投票

您可以将模板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
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.