我正在使用
还有更方便的方法来计算一个字符串中的行数吗?
split('\n')
来获取一个字符串中的行,并发现 ''.split()
返回一个空列表,[]
,而 ''.split('\n')
返回 ['']
。这种差异有没有特定的原因?还有更方便的方法来计算一个字符串中的行数吗?
split('\n')
来获取一个字符串中的行,发现'' .split()
返回一个空列表[]
,而'' .split('\n')
返回['']
。
str.split()
方法有两种算法。如果没有给出参数,则它会在连续的空格上进行分割。但是,如果给出参数,则将其视为单个分隔符,没有重复的运行。\n
的参数)将产生第一个空字段。考虑如果您编写了'\n'.split('\n')
,您将获得两个字段(一个拆分,给您两个半部分)。>>> data = '''\
Shasta California 14,200
McKinley Alaska 20,300
Fuji Japan 12,400
'''
>>> for line in data.splitlines():
print(line.split())
['Shasta', 'California', '14,200']
['McKinley', 'Alaska', '20,300']
['Fuji', 'Japan', '12,400']
>>> data = '''\
Guido,BDFL,,Amsterdam
Barry,FLUFL,,USA
Tim,,,USA
'''
>>> for line in data.splitlines():
print(line.split(','))
['Guido', 'BDFL', '', 'Amsterdam']
['Barry', 'FLUFL', '', 'USA']
['Tim', '', '', 'USA']
str.split(delimiter)
方法也是这样的。>>> ''.split(',') # No cuts
['']
>>> ','.split(',') # One cut
['', '']
>>> ',,'.split(',') # Two cuts
['', '', '']
str.count()
,另一种使用str.splitlines()
。除非最后一行缺少\n
,否则两种方法都会给出相同的答案。如果缺少最后一个换行符,则str.splitlines
方法将给出准确的答案。一种更快速且准确的技术使用计数方法,但然后纠正最后一个换行符:>>> data = '''\
Line 1
Line 2
Line 3
Line 4'''
>>> data.count('\n') # Inaccurate
3
>>> len(data.splitlines()) # Accurate, but slow
4
>>> data.count('\n') + (not data.endswith('\n')) # Accurate and fast
4
ps_aux_header = 'USER PID %CPU %MEM VSZ'
patient_header = 'name,age,height,weight'
fields = line.split()
或fields = line.split(',')
时,人们往往能够正确地解释这些语句为"将一行分割成字段"。.split(arg)
在分隔符前后没有字符时返回None
而不是空字符串?谢谢 - undefined根据文档,似乎这就是它应该工作的方式:
使用指定的分隔符拆分空字符串将返回
['']
。如果未指定sep或sep为None,则会应用不同的拆分算法:连续的空格被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。因此,使用None作为分隔符拆分空字符串或仅由空格组成的字符串将返回[]。
因此,为了使其更清晰,split()
函数实现了两种不同的拆分算法,并使用参数的存在来决定要运行哪一个。可能是因为允许对无参数的算法进行优化而不是其他带有参数的算法;我不确定。
.split()
在没有参数的情况下尝试变得聪明。它会将任何空格、制表符、空格、换行等都分隔开,并跳过所有由此产生的空字符串。
>>> " fii fbar \n bopp ".split()
['fii', 'fbar', 'bopp']
.split()
用于从字符串中提取单词,而有参数的.split()
只是将一个字符串分割成多个部分。对于那些真正想要避免调用空字符串的split方法返回['']
默认行为的人,这里有两种可能的一行解决方案:
list_ = s.split(*list(sep if s.count(sep) else []))
# Or this
list_ = s.split(sep) if s != "" else []
以下是如何在实际示例中使用第一个方法:
import os
sep = os.linesep # Split char
s_empty = ""
empty = s_empty.split(*list(sep if s_empty.count(sep) else []))
s_nonempty = f"a{sep}b"
nonempty = s_nonempty.split(*list(sep if s_nonempty.count(sep) else []))
print(f"Empty string: {empty}, non-empty string: {nonempty}")
count()
函数:s = "Line 1\nLine2\nLine3"
n_lines = s.count('\n') + 1
>>> print str.split.__doc__
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
\n
:line_count = some_string.count('\n') + some_string[-1] != '\n'
\n
结束的情况,尽管这意味着Hello, World!
和Hello, World!\n
有相同的行数(我觉得这很合理),否则你可以将\n
的计数加上1
。要计算行数,可以数换行符的数量:
n_lines = sum(1 for s in the_string if s == "\n") + 1 # add 1 for last line
编辑:
另一个答案 带有内置的 count
更加合适,实际上
count
方法外,布尔值也可以相加(实际上,它们是int
的子类),因此生成器表达式可以写成 sum(s == "\n" for s in the_string)
。 - lvc