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

时间:2015-05-24 21:04:40

标签: python python-2.7 multilinestring

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.

4 个答案:

答案 0 :(得分:4)

With find or index?

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

答案 1 :(得分: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.

答案 2 :(得分: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.

答案 3 :(得分: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]))