Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this text processing code Pythonic?

Tags:

python

text

I need to take a line of text (words) and split it in half at the first space following the midpoint of the line; e.g.:

The quick brown fox jumps over the lazy dog.
                         ^

The mid-point of the line above is at position 22, and the line is split at the space following the word "jumps".

I would appreciate if you could look at the following code and tell me if it is Pythonic. If not, please suggest the correct way. Thank you. (PS: I come from a C++ background.)

    midLine = len(line) / 2                  # Locate mid-point of line.
    foundSpace = False
    # Traverse the second half of the line and look for a space.
    for ii in range(midLine):
        if line[midLine + ii] == ' ':        # Found a space.
            foundSpace = True
            break
    if (foundSpace == True):
        linePart1 = line[:midLine + ii]      # Start of line to location of space - 1.
        linePart2 = line[midLine + ii + 1:]  # Location of space + 1 to end of line.
like image 747
Sabuncu Avatar asked Sep 21 '26 19:09

Sabuncu


1 Answers

Pythonic is to use builtin functions where available. string.index does the job here.

def half(s):
    idx = s.index(' ', len(s) / 2)
    return s[:idx], s[idx+1:]

This will raise a ValueError if there's no suitable place to break the string. You may have to adjust the code if that's not what you want.

like image 159
Paul Hankin Avatar answered Sep 24 '26 07:09

Paul Hankin