【问题标题】:how to insert variable into string by position如何按位置将变量插入字符串
【发布时间】:2020-09-02 14:32:42
【问题描述】:

如何按位置将变量插入字符串, 比如在string中插入a

string = "Hello World"

a = '@'

position = 3

输出 >>> Hel@lo World

【问题讨论】:

  • 你试过了吗?你的尝试出了什么问题?
  • string[:position] + a + string[position:]

标签: python string variables position


【解决方案1】:
str_1="Hello World"
st=list(str_1)
st.insert(pos,a)
str_1="".join(st)

您可以先将列表转换为字符,然后将其存储在一个列表中,您可以在其中添加任意数量的元素,然后最后使用 .join() 获取修改后的字符串

【讨论】:

    【解决方案2】:

    你可以使用切片:

    a = '@'
    position = 3
    string = "Hello World"
    new = string[:position] + a + string[position:]
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      str_1 = "Hello World"
      
      def insert_str(org_str, insert_str, pos):
          str_2 = list(org_str)
          str_2.insert(pos, insert_str)
          new_string = "".join(str_2)
          return new_string
      
      a = '@'
      position = 3
      
      new_string = insert_str(org_str=str_1, insert_str=a, pos=position)
      print(new_string)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-08
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        相关资源
        最近更新 更多