本文介绍了查找字符串中有多少行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个 python 电影播放器/制作器,我想在多行字符串中查找行数.我想知道是否有任何内置函数或函数我可以编写代码来执行此操作:
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:
x = """
line1
line2 """
getLines(x)
推荐答案
If newline is '\n'
then nlines = x.count('\n')
.
If newline is '\n'
then nlines = x.count('\n')
.
优点是您不需要像 .split('\n')
那样创建不必要的列表(结果可能因 x.endswith('\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')
).
str.splitlines()
接受更多字符作为换行符:nlines = len(x.splitlines())
.
这篇关于查找字符串中有多少行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!