Python 查找字符串中有多少行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34846413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:36:34  来源:igfitidea点击:

Find how many lines in string

pythonpython-3.x

提问by falcon user

I am creating a python movie player/maker, and I want to find the number of lines in a multiple line string. I was wondering if there was any built in function or function I could code to do this:

我正在创建一个 python 电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或函数我可以编写代码来做到这一点:

x = """
line1
line2 """

getLines(x)

采纳答案by jfs

If newline is '\n'then nlines = x.count('\n').

如果换行是'\n'那么nlines = x.count('\n')

The advantage is that you don't need to create an unnecessary list as .split('\n')does (the result may differ depending on x.endswith('\n')).

优点是您不需要像.split('\n')这样创建不必要的列表(结果可能因 不同而不同x.endswith('\n'))。

str.splitlines()accepts more characters as newlines: nlines = len(x.splitlines()).

str.splitlines()接受更多字符作为换行符:nlines = len(x.splitlines()).

回答by heemayl

You can do:

你可以做:

len(x.split('\n'))

回答by TigerhawkT3

You can split()it and find the length of the resulting list:

你可以split()找到结果的长度list

length = len(x.split('\n'))

Or you can count()the number of newline characters:

或者您可以count()设置换行符的数量:

length = x.count('\n')

Or you can use splitlines()and find the length of the resulting list:

或者您可以使用splitlines()并找到结果的长度list

length = len(x.splitlines())

回答by c z

SPAM\nEGGS\nBEANS= Three lines, two line breaks

SPAM\nEGGS\nBEANS= 三行,两个换行符

So if counting lines, use + 1, or you'll make a fencepost error:

因此,如果计算线数,请使用+ 1,否则您将出现围栏错误

x.count( "\n" ) + 1