在 Python 中的给定索引处插入一些字符串到给定的字符串中

问题描述:

我是 Python 新手,面临一个问题:如何在现有字符串中插入一些字段?

I am newbie in Python facing a problem: How to insert some fields in already existing string?

例如,假设我从包含以下内容的任何文件中读取了一行:

For example, suppose I have read one line from any file which contains:

line = "Name Age Group Class Profession"

现在我必须在 Class 字段之前的同一行中插入 3rd Field(Group) 3 次.这意味着输出行应该是:

Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the output line should be:

output_line = "Name Age Group Group Group Group Class Profession"

我可以轻松检索第三个字段(使用 split 方法),但请告诉我插入字符串的最简单方法?

I can retrieve 3rd field easily (using split method), but please let me know the easiest way of inserting into the string?

一个经常让 Python 新手感到厌烦但其他海报没有明确说明的重要点是 Python 中的字符串是不可变的——你不能永远就地修改它们.

An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't ever modify them in place.

在 Python 中处理字符串时,您需要重新训练自己,以便不要思考我如何修改这个字符串?"相反,您在想我如何创建一个新的字符串,其中包含我已经获得的部分?"

You need to retrain yourself when working with strings in Python so that instead of thinking, "How can I modify this string?" instead you're thinking "how can I create a new string that has some pieces from this one I've already gotten?"