简体   繁体   English

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

[英]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.我正在尝试编写一个自动生成多个 URL 的小程序,每个 URL 基本相同,唯一的区别是在每个 URL 中插入了不同的外语缩写。

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所以我想在“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

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,你可以制作一个模板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.

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