如何检查一行是否以python中的单词或制表符或空格开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28957573/
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
How to check whether a line starts with a word or tab or white space in python?
提问by Pavan Chakravarthy
can some one tell me how can i check whether a line starts with string or space or tab? I tried this, but not working..
有人可以告诉我如何检查一行是以字符串还是空格或制表符开头?我试过这个,但不工作..
if line.startswith(\s):
outFile.write(line);
below is the samp data..
下面是样本数据..
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"*
采纳答案by Avinash Raj
To check a line starts with space or tab.
检查一行以空格或制表符开头。
if re.match(r'\s', line):
\s
matches newline character also.
\s
也匹配换行符。
OR
或者
if re.match(r'[ \t]', line):
To check a line whether it starts with a word character or not.
检查一行是否以单词字符开头。
if re.match(r'\w', line):
To check a line whether it starts with a non-space character or not.
检查一行是否以非空格字符开头。
if re.match(r'\S', line):
Example:
例子:
>>> 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'>
>>>
回答by mgilson
To check if a line starts with a space or a tab, you can pass a tuple to .startswith
. It will return True
if the string starts with any element in the tuple:
要检查一行是以空格还是制表符开头,您可以将元组传递给.startswith
. True
如果字符串以元组中的任何元素开头,它将返回:
if line.startswith((' ', '\t')):
print('Leading Whitespace!')
else:
print('No Leading Whitespace')
e.g:
例如:
>>> ' foo'.startswith((' ', '\t'))
True
>>> ' foo'.startswith((' ', '\t'))
True
>>> 'foo'.startswith((' ', '\t'))
False
回答by vks
whether a line starts with a word or tab or white space in python
在python中一行是否以单词或制表符或空格开头
if re.match(r'[^ \t].*', line):
print "line starts with word"
回答by Alexander
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 '
Hopefully this suffices without explanation.
希望这无需解释就足够了。
回答by Fitzy
Basically the same as Alexander's answer, but expressed as a one liner without a regex.
基本上与亚历山大的回答相同,但表示为没有正则表达式的单行。
from string import whitespace
if line.startswith(tuple(w for w in whitespace)):
outFile.write(line);