可以有人告诉我如何检查一行是否以字符串或空格或制表符开头?我试过这个,但没有工作..
if line.startswith(\s):
outFile.write(line);
Run Code Online (Sandbox Code Playgroud)
以下是samp数据..
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"*
Run Code Online (Sandbox Code Playgroud)
检查行以空格或制表符开头.
if re.match(r'\s', line):
Run Code Online (Sandbox Code Playgroud)
\s 匹配换行符也.
要么
if re.match(r'[ \t]', line):
Run Code Online (Sandbox Code Playgroud)
检查一行是否以单词字符开头.
if re.match(r'\w', line):
Run Code Online (Sandbox Code Playgroud)
检查一行是否以非空格字符开头.
if re.match(r'\S', line):
Run Code Online (Sandbox Code Playgroud)
例:
>>> 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'>
>>>
Run Code Online (Sandbox Code Playgroud)
要检查行是否以空格或制表符开头,您可以将元组传递给.startswith.True如果字符串以元组中的任何元素开头,它将返回:
if line.startswith((' ', '\t')):
print('Leading Whitespace!')
else:
print('No Leading Whitespace')
Run Code Online (Sandbox Code Playgroud)
例如:
>>> ' foo'.startswith((' ', '\t'))
True
>>> ' foo'.startswith((' ', '\t'))
True
>>> 'foo'.startswith((' ', '\t'))
False
Run Code Online (Sandbox Code Playgroud)
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 '
Run Code Online (Sandbox Code Playgroud)
希望这无需解释就足够了。
| 归档时间: |
|
| 查看次数: |
23646 次 |
| 最近记录: |