Shiva's Weblog

Various things I am putting up for my reference. Hope its useful to you as well.

challa.net | Tech weblog |  Lyrics

Python tidbits

By Shiva Challa Shiva's Weblog

Wednesday, April 29, 2015

Python

Open a file:

with open('filename.txt', 'r') as f:
first_line = f.readline()
print "1st line = ", first_line
 

Python REGEX sample

import re

def find(pat,text):
....match = re.search(pat,text)
....if match: print match.group()
....else: print "not found"

find('iig','piiig')
find('x...g','called piiig')
find(r'[\w.]+@[\w.]+','blah shiva@mail.com blah @.')
find(r"[\w']+","dhel afkljsl ")

# left to right
# . (dot) any character
# \w word character
# \d digit
# \s whitespace
# \S non-whitespace chars
# r = treat the following quoted string as raw string

def find_all(pat,text):
....## re.findall finds all the patterns in the provided text
....re.findall(r'([\w.]+)@([\w.]+)','blash .shiva.ch@mail.com blah')

Ads by Google

Made with CityDesk