1

I have the foll. string:

'    Y   M   D     PDSW      RSPC      NPPC       NEE'

Each element in the string corresponds to a column in a csv file. Is there a way (aside from for loops), of getting the width of each column from this string? E.g. Th first column has a width of 5 (' Y'), the next has a width of 4(' M')...

5
  • .. And what is wrong with doing it the way you suggest: with a loop? Commented Oct 12, 2015 at 20:51
  • nothing wrong per se, just hoping if there is a more pythonic way Commented Oct 12, 2015 at 20:52
  • 1
    Is using a regex also Not The Python Way? (Guess based on stackoverflow.com/q/4995892/2564301 - you'd just have to capture sets of n spaces followed by m not-spaces). Commented Oct 12, 2015 at 20:55
  • wouldn't regex eat up the spaces too? Commented Oct 12, 2015 at 20:55
  • 1
    The accepted answer suggests not. There is also an alternative that uses findall in lieu of split. Commented Oct 12, 2015 at 20:57

1 Answer 1

5

Maybe something like:

>>> text = '    Y   M   D     PDSW      RSPC      NPPC       NEE'
>>> cols = re.findall('\s+\S+', text)
>>> [len(col) for col in cols]
[5, 4, 4, 9, 10, 10, 10]

So - assume the columns (right-aligned) are one or more spaces followed by one or more non-space, then take the lengths of the resulting strings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.