如何获取多行字符串中第一行的长度? [英] How do I get the length of the first line in a multi line string?
问题描述
我有一个由脚本生成的多行字符串,该脚本从图像创建 ASCII 艺术.它创建一行,然后添加 \r
并继续.如何在不使用正则表达式的情况下获得第一行的长度,或者在它说 \r
之前?最好是代码具有相当的可读性.
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.
推荐答案
尝试:
first, _, _ = s.partition('\r')
k = len(first)
如果你不需要字符串,你可以使用index
:
If you don't need the string, you can just use index
:
k = s.index('\r')
这是可行的,因为 s.index('\r')
包含最低索引 k
,其中 s[k] == '\r'
-- 这意味着第一行正好有 k
个字符(s[0]
到 s[k-1]
), 在回车符之前.
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.
这篇关于如何获取多行字符串中第一行的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!