qwerty
qwerty

Reputation: 93

Inserting a period after each character in a loop

Say I have a string tex = "somestring"

I need to create a loop that will create multiple copies of that string, each one with a period added after a character, starting after the first character and ending it before the last

Something like

for i in range (1, len(tex)-2):
    tex = ....
    print(tex)

The output needs to be:

s.omestring
so.mestring
som.estring
...
somestrin.g

I tried using tex = '.'.join(tex[i+1] for i in range (1, len(tex)-2, 1)) from other questions but that adds a period after every character only once, resulting in s.o.m.e.s.r.i.n.g

Maybe splitting the string into a list of characters would help, but I'm not sure how to approach it from that way.

Upvotes: 2

Views: 791

Answers (3)

Riccardo Bucco
Riccardo Bucco

Reputation: 15384

Here is a possible one line solution:

s = 'somestring'
print(*(s[:i] + '.' + s[i:] for i in range(1, len(s))), sep='\n')

Output:

s.omestring
so.mestring
som.estring
some.string
somes.tring
somest.ring
somestr.ing
somestri.ng
somestrin.g

Upvotes: 3

Talico17
Talico17

Reputation: 29

text = "something"

for char in range(1, len(text)):
    print(text[:char] + "." + text[char:])

Hope i was helpful!

Upvotes: 2

kuro
kuro

Reputation: 3226

Simply use this -

for i in range (1, len(tex)):
     print(tex[:i]+"."+tex[i:])

Upvotes: 3

Related Questions