简体   繁体   中英

How do I insert a string into a specific section of a larger string?

I'm trying to write a little program that automatically generates a number of URLs, each basically the same except with the one difference of having a different foreign language abbreviation inserted into each one.

For example, I have this code:

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']

So I want to insert each of those language abbreviations into the base_url value at the spot before "wiki," leading to

https://habitica.fandom.com/da/wiki/Special:WhatLinksHere
https://habitica.fandom.com/de/wiki/Special:WhatLinksHere
https://habitica.fandom.com/es/wiki/Special:WhatLinksHere

and so forth.

How should I go about doing this? Is there a fairly general way, or do I need to get into some very detailed code about the specific text of the strings?

Thanks! John

You could just make a template str ing and format it like,

>>> 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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM