【问题标题】:How to put a str into another str, but on a specific digit in the other str? [duplicate]如何将一个 str 放入另一个 str 中,但放在另一个 str 中的特定数字上? [复制]
【发布时间】:2022-01-27 18:58:44
【问题描述】:

(示例:)

a = "-"
b = "testtest"

我想将 a = "-" 放在 bstring 的 4 位之后(所以在第一个和第二个“测试”之间)。 所以它应该总是在前 4 位之后(如果 b-str 更长,它不应该只在前 4 位。

【问题讨论】:

  • b[:4] + a + b[4:]?
  • 我无法创建答案,因为问题已关闭(我认为这是一个错误)。我尝试在这里发布我的代码,但格式会很糟糕。 a = '-' b = 'testtesttest' number_of_dashes = (len(b)-1)//4 c = '' for i in range(number_of_dashes): c = c + b[i*4:(i+1)*4] + a c = c + b[number_of_dashes*4:] print(c)
  • @Blupper 是的,我也不想关闭它,但遗憾的是它得到了......但无论如何谢谢:D
  • @Chaos 我提出的解决方案对你有用吗?

标签: python


【解决方案1】:

在字符串中应用slicing

index = 4
a = '-'
b = 'testtest'
c = b[:index] + a + b[index:]

【讨论】:

  • 这行得通,谢谢,但也只能在第一个 4 位上,如果 b str 是例如 16 位长,你怎么能做到这一点,我想要每 4 个“-”?
  • @Chaos 你能更新你的问题吗?
  • 它已经在我的问题中了
【解决方案2】:
a = "-"
b = "testtest"

c = b[:4]+a+b[4:]
print (c)

【讨论】:

    猜你喜欢
    • 2019-05-25
    • 2019-10-09
    • 2016-07-15
    • 2023-04-01
    • 1970-01-01
    • 2015-12-13
    • 2012-11-08
    • 1970-01-01
    • 2022-06-12
    相关资源
    最近更新 更多