-3
def Change(_text):
    L = len(_text)
    _i = 2
    _text[_i] = "*"
    _i += 2
    print(_text)

How can I add a mark e.g:* every two Index In String

Taku
  • 31,927
  • 11
  • 74
  • 85
Alex
  • 3
  • 3
  • duplicate maybe: https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – Ammar Apr 01 '17 at 19:52
  • 1
    Possible duplicate of [What is the most "pythonic" way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – Shea Hunter Belsky Apr 01 '17 at 22:33

2 Answers2

0

Why are you using _ in your variables? If it is for any of these reasons then you are OK, if it is a made up syntax, try not to use it as it might cause unnecessary confusion.

As for your code, try:

def change_text(text): 
    for i in range(len(text)):
        if i % 2 == 0: # check if i = even (not odd)
            print(text[:i] + "*" + text[i+1:])

When you run change_text("tryout string") the output will look like:

*ryout string
tr*out string
tryo*t string
tryout*string
tryout s*ring
tryout str*ng
tryout strin*

If you meant something else, name a example input and wished for output.

See How to create a Minimal, Complete, and Verifiable example

PS: Please realize that strings are immutable in Python, so you cannot actually change a string, only create new ones from it.. if you want to actually change it you might be better of saving it as a list for example. Like they have done here.

Community
  • 1
  • 1
Montmons
  • 1,416
  • 13
  • 44
0

Are you trying to separate every two letters with an asterix?

testtesttest
te*st*te*st*te*st

You could do this using itertools.zip_longest to split the string up, and '*'.join to rebuild it with the markers inserted

from itertools import zip_longest

def add_marker(s):
    return '*'.join([''.join(x) for x in zip_longest(*[iter(s)]*2, fillvalue='')])
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96