0

(Example:)

a = "-"
b = "testtest"

I want to put the a = "-" after 4 digits of the bstring (so between the first and second "test"). So it should be always after the first 4 digits (if the b-str is longer, it shouldn't just go at the first 4th digit.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • so in the console, it should be "test-test" then (or if it is like 5 "test", should be 4 "-" in between. –  Jan 27 '22 at 10:51
  • 2
    `b[:4] + a + b[4:]`? – Olvin Roght Jan 27 '22 at 10:52
  • I can't create an answer because the question is closed (which in my opinion is a mistake). I try to post my code here, the formatting will be terrible though. `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 Jan 27 '22 at 11:12
  • @Blupper yeah, I also didn't want to close it tho, but it sadly got.. but thanks anyway:D –  Jan 27 '22 at 11:30
  • @Chaos did the solution I proposed work for you? – Blupper Jan 27 '22 at 12:04
  • @Chaos, it closed because your question is a duplicate. Use search box on the top of the page. – Olvin Roght Jan 27 '22 at 14:17

2 Answers2

2

Apply slicing in a string

index = 4
a = '-'
b = 'testtest'
c = b[:index] + a + b[index:]
Alb
  • 1,063
  • 9
  • 33
  • This works thanks, but also only on the first 4th digit, how can you do it if the b str is for example 16 digits long, and I want every 4th the "-"? –  Jan 27 '22 at 10:57
  • @Chaos could you update your question for that? – Alb Jan 27 '22 at 10:59
  • it is in my question already in tho –  Jan 27 '22 at 11:01
2
a = "-"
b = "testtest"

c = b[:4]+a+b[4:]
print (c)
David
  • 45
  • 1
  • 9