且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取多行字符串中第一行的长度?

更新时间:2023-12-04 11:34:58

尝试:

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.