[英]How to check whether a line starts with a word or tab or white space in python?
有人能告诉我如何检查一行是以字符串、空格还是制表符开头的吗? 我试过这个,但没有工作..
if line.startswith(\s):
outFile.write(line);
下面是示例数据..
female 752.9
external 752.40
specified type NEC 752.49
internal NEC 752.9
male (external and internal) 752.9
epispadias 752.62"
hidden penis 752.65
hydrocele, congenital 778.6
hypospadias 752.61"*
检查行以空格或制表符开头。
if re.match(r'\s', line):
\\s
匹配换行符。
要么
if re.match(r'[ \t]', line):
检查一行是否以单词字符开头。
if re.match(r'\w', line):
检查一行是否以非空格字符开头。
if re.match(r'\S', line):
例:
>>> re.match(r'[ \t]', ' foo')
<_sre.SRE_Match object; span=(0, 1), match=' '>
>>> re.match(r'[ \t]', 'foo')
>>> re.match(r'\w', 'foo')
<_sre.SRE_Match object; span=(0, 1), match='f'>
>>>
要检查行是否以空格或制表符开头,您可以将元组传递给.startswith
。 如果字符串以元组中的任何元素开头,它将返回True
:
if line.startswith((' ', '\t')):
print('Leading Whitespace!')
else:
print('No Leading Whitespace')
例如:
>>> ' foo'.startswith((' ', '\t'))
True
>>> ' foo'.startswith((' ', '\t'))
True
>>> 'foo'.startswith((' ', '\t'))
False
from string import whitespace
def wspace(string):
first_character = string[0] # Get the first character in the line.
return True if first_character in whitespace else False
line1 = '\nSpam!'
line2 = '\tSpam!'
line3 = 'Spam!'
>>> wspace(line1)
True
>>> wspace(line2)
True
>>> wspace(line3)
False
>>> whitespace
'\t\n\x0b\x0c\r '
希望这没有解释就足够了。
行是否以python中的单词或制表符或空格开头
if re.match(r'[^ \t].*', line):
print "line starts with word"
基本上与亚历山大的答案相同,但表达为没有正则表达式的单线。
from string import whitespace
if line.startswith(tuple(w for w in whitespace)):
outFile.write(line);
另一种匹配任何空白字符的方法:
if line[:1].isspace():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.