3

I have a multiline string generated by a script that creates ASCII art from an image. It creates a line, then adds \r and keeps going. How do I get the length of the first line, or before it says \r without using regex? Preferably the code is fairly readable.

Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
  • What's wrong with regex? I think they would be an appropriate solution. – skrrgwasme May 24 '15 at 21:11
  • Is there another solution? I'd rather not use regex just because I haven't learned it yet and I'd rather my program contain only stuff I understand. – Luke Taylor May 24 '15 at 21:12

4 Answers4

5

With find or index?

>>> 'abcfoo\rhahahahaha'.find('\r')
6
>>> 'abcfoo\rhahahahaha'.index('\r')
6
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
3

Try:

first, _, _ = s.partition('\r')
k = len(first)

If you don't need the string, you can just use index:

k = s.index('\r')

This works because s.index('\r') contains the lowest index k for which s[k] == '\r' -- this means there are exactly k characters (s[0] through s[k-1]) on the first line, before the carriage return character.

Lynn
  • 10,425
  • 43
  • 75
  • I accepted this because having the whole string before is useful. I'm using PIL to find the size, in pixels, of a string. I'm using a monospaced font, so it shouldn't matter whether I find the size of the whole string or the size of one character times the length of the line, but I feel safer finding the length of the whole line. – Luke Taylor May 24 '15 at 21:47
1
import string
string.split(yourString, '\r')
length = len(string[0])

So what we have here is straight forward. We take your string and we split it as soon as we get the /r tag. Then, since all strings terminated with /r are in an array we simply count the first captured string in the array and assign it to the var length.

Scott Johnson
  • 369
  • 2
  • 15
  • 1
    Why don't you edit this, add a line that says `length = len(string[0])`? That would be a valid response and work well. – Luke Taylor May 24 '15 at 21:30
  • Well you got so many great answers already that by the time I came to edit it it had already been answered lol – Scott Johnson May 24 '15 at 21:32
  • @ScottJohnson You should edit your answer and add some description. With a description, your answer will be here for posterity and future users with the same issue as the OP's might find your answer useful and upvote it. – Luís Cruz May 24 '15 at 23:33
1

Just in case you need yet another solution..:

with open('test.txt','r') as f:
    t = f.read()
    l = t.splitlines()
    print(len(l[0]))
Oliver S.
  • 39
  • 6