【问题标题】:can you insert a string into another string by user input in python?你可以通过python中的用户输入将一个字符串插入另一个字符串吗?
【发布时间】:2021-08-07 02:39:11
【问题描述】:

请有人帮助我! 我正在尝试制作一个简单的程序,用户可以在其中将字符串插入到已经存在的字符串中(对不起,如果这令人困惑!)

这是我的代码:

firststring = input("enter a string: ")
secondstring = input("enter a second string: ")
position = input("where would you like to place the second string?")
if possition.isdigit == True:
    print() <--#help me here

有人可以帮帮我吗?

【问题讨论】:

  • 你不能在另一个字符串中插入一个字符串,因为字符串是不可变的。您需要根据位置获取字符串切片并将它们连接起来。

标签: python string input insert


【解决方案1】:

您可以使用字符串切片来打印第一个字符串的第一部分,然后是第二个字符串,然后是第一个字符串的其余部分。

position = int(input("where would you like to place the second string?"))
print(firststring[:position] + secondstring + firststring[position:]

【讨论】:

    【解决方案2】:

    您可以使用列表切片。 firststring[:int(position)] 将获取所有字符直到特定索引,然后连接第二个字符串,firststring[int(position):] 将获取从索引位置到末尾的所有字符

    position = input("where would you like to place the second string?")
    if position.isdigit() :
        string3=firststring[:int(position)]+secondstring+firststring[int(position):]
        print(string3)
    

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 2012-09-25
      • 2011-05-13
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2012-08-14
      相关资源
      最近更新 更多