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"*
To check a line starts with space or tab.
if re.match(r'\s', line):
\s
matches newline character also.
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'>
>>>
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:
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
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.
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);
whether a line starts with a word or tab or white space in python
if re.match(r'[^ \t].*', line):
print "line starts with word"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With