My program is supposed to replace all sets of 4 spaces with a tab but it only seems to be editing the first line then skipping the rest of the lines. "work_string" is defined via another function which takes and saves an entire files input into one string. I just can't get my replacing function to act on multiple lines instead of just the first one.

Here's my replacing function, anyone have an idea of how to get it to act on every line of "work_string"?

def space_to_tab(work_string):
    s_to_tab = 4

    whitespace = work_string[ : len(work_string) - len(work_string.lstrip())]
    whitespace = whitespace.replace(REAL_SPACE * s_to_tab, REAL_TAB)
    whitespace = whitespace.lstrip(REAL_SPACE)
    result = whitespace + (work_string.lstrip())
    return result

You can make it a helper function for a function which acts on a full text:

def _space_to_tab(work_string):
    """Replace spaces with tab at the beginning of a line of text
    """
    s_to_tab = 4

    whitespace = work_string[ : len(work_string) - len(work_string.lstrip())]
    whitespace = whitespace.replace(REAL_SPACE * s_to_tab, REAL_TAB)
    whitespace = whitespace.lstrip(REAL_SPACE)
    result = whitespace + (work_string.lstrip())
    return result

def space_to_tab(work_string):
    """Replace spaces with tab at the beginning of each line of a text
    """
    lines = work_string.split('\n')
    lines = (_space_to_tab(line) for line in lines)
    return '\n'.join(lines)

Ok, a while loop should do the trick

def space_to_tab(work_string):
    """Replace spaces with tab at the beginning of each line of a text
    """
    result = []
    s_to_tab = 4
    space = REAL_SPACE * s_to_tab
    for line in work_string.split('\n'):
        rest = line.lstrip()
        white = line[:len(line) - len(rest)]
        white = white.replace(space, REAL_TAB).lstrip(REAL_SPACE)
        result.append(white + rest)
    return '\n'.join(result)

Wow, that was such a big help. I was thinking of using a for loop but I couldn't find a way to implement it! Now I just have to edit it to work with my other functions and it should do the trick. Thanks so much.

This article has been dead for over six months. Start a new discussion instead.