Python 中向一个字符串中插入字符串

Muhammad Waiz Khan 2023年1月30日 2021年2月7日
  1. 在 Python 中使用 string.find() 方法在字符串中插入字符串
  2. 在 Python 中使用 list.insert() 方法将字符串插入到一个字符串之中
Python 中向一个字符串中插入字符串

本教程将为大家讲解在现有字符串中插入字符串的多种方法。我们应该知道,在 Python 中,字符串是不可变的,这意味着在 Python 中不能改变或修改一个字符串。

关于字符串的插入,我们可以做的是创建一个新的字符串,并进行所需的修改,比如将原来的字符串拆分,然后在其中插入一个新的字符串。

在 Python 中使用 string.find() 方法在字符串中插入字符串

我们首先使用 string.find() 方法获取字符串中的子字符串索引,之后我们需要插入另一个字符串。在得到子字符串索引后,我们对原字符串进行拆分,然后将拆分后的字符串和我们需要插入的字符串使用+ 运算符进行连接,得到所需的字符串。

示例代码:

my_string = 'Hello, what are doing?'
index = my_string.find('doing')
final_string = my_string[:index] + 'you ' + my_string[index:]
print(final_string)

输出:

Hello, what are you doing?

在 Python 中使用 list.insert() 方法将字符串插入到一个字符串之中

我们可以使用 string.split() 函数将原来的字符串分割成一个列表后,将字符串插入到另一个字符串中。在将字符串转换为列表后,我们可以使用 list.insert() 函数将字符串插入到列表所需的索引处。

在拆分和添加所需的字符串后,我们可以使用 string.join() 函数将列表转换回字符串,得到所需的字符串。

示例代码:

my_string = 'Hello, what are doing'

split_strings = my_string.split()
split_strings.insert(3, 'you')
final_string = ' '.join(split_strings)
print(final_string)

输出:

Hello, what are you doing?

相关文章 - Python String