How do I get the length of the first line in a multi-line string?

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 moving. How do I get the length of the first line or before it produces \r

without using regex? The code is preferably readable enough.

+3


source to share


4 answers


Try:

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

      

If you don't need a string, you can simply use index

:



k = s.index('\r')

      

This works because it s.index('\r')

contains the lowest index k

for which s[k] == '\r'

- it means there are exactly k

characters ( s[0]

thru s[k-1]

) in the first line before the carriage returns a character.

+3


source


C find

or index

?



>>> 'abcfoo\rhahahahaha'.find('\r')
6
>>> 'abcfoo\rhahahahaha'.index('\r')
6

      

+4


source


import string
string.split(yourString, '\r')
length = len(string[0])

      

So what we have here is straight forward. We take your string and we strip it as soon as we get the / r tag. Then, since all the lines enclosed with / r are in the array, we just count the first captured line in the array and assign the length to var.

+1


source


Just in case you need one more solution ..:

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

      

+1


source







All Articles