How to check whether a line starts with a word or tab or white space in python?

Question:

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"*
Asked By: Pavan Chakravarthy

||

Answers:

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'>
>>> 
Answered By: Avinash Raj

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
Answered By: mgilson

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"
Answered By: vks
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
'tnx0bx0cr '

Hopefully this suffices without explanation.

Answered By: Alexander

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);
Answered By: Fitzy

Yet another approach to match any whitespace character:

if line[:1].isspace():
Answered By: Kexanone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.