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
Solution 1:
With find
or index
?
>>>'abcfoo\rhahahahaha'.find('\r')
6
>>>'abcfoo\rhahahahaha'.index('\r')
6
Solution 2:
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.
Solution 3:
Just in case you need yet another solution..:
withopen('test.txt','r') as f:
t = f.read()
l = t.splitlines()
print(len(l[0]))
Solution 4:
importstringstring.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.
Post a Comment for "How Do I Get The Length Of The First Line In A Multi Line String?"