0

How do I change a string so that every 5 characters there will be a space in between? However, I do not wish to have space at the beginning or at the end.

for example

"Yohomeyoverstack" will be "Yohom eyove rstac k"

"two"  will be "two"
Gelineau
  • 2,031
  • 4
  • 20
  • 30
syagj
  • 19
  • 2

2 Answers2

1

Using slicing

Ex:

s = "Yohomeyoverstack"
print( " ".join([s[i:i+5] for i in range(0, len(s), 5)]) )

Output:

Yohom eyove rstac k
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • But what if the string have white spaces in it. Like `s = "Yohomeyov erstack"`. The output will have spaces in the begining and end – Sreeram TP Jul 19 '18 at 06:11
1

You can do this with the help of slicing.

data = "Yohomeyoverstack"

stripped = "".join(data.split())

splitted = " ".join([stripped[i:i+5] for i in range(0, len(stripped), 5)])

print(splitted)

This solution will work even if there are whitespaces in the string

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108