Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"*
like image 816
Pavan Chakravarthy Avatar asked Mar 10 '15 06:03

Pavan Chakravarthy


5 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'>
>>> 
like image 121
Avinash Raj Avatar answered Oct 19 '22 20:10

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
like image 41
mgilson Avatar answered Oct 19 '22 18:10

mgilson


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.

like image 44
Alexander Avatar answered Oct 19 '22 18:10

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);
like image 34
Fitzy Avatar answered Oct 19 '22 18:10

Fitzy


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"
like image 2
vks Avatar answered Oct 19 '22 18:10

vks