Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 904
Luke Taylor Avatar asked Dec 10 '25 20:12

Luke Taylor


2 Answers

With find or index?

>>> 'abcfoo\rhahahahaha'.find('\r')
6
>>> 'abcfoo\rhahahahaha'.index('\r')
6
like image 116
Stefan Pochmann Avatar answered Dec 13 '25 10:12

Stefan Pochmann


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.

like image 38
Lynn Avatar answered Dec 13 '25 09:12

Lynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!