Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Tuesday, June 28, 2011

Searching for IP address using regular expression

This snippet finds an IP address in a string using regex:
import re
ip = re.compile('(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}'
                +'(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))')

match = ip.search("Your ip address is 192.168.0.1, have fun!")
if match:
 print 'IP address found:',
 print match.group(), # matching substring
 print 'at position',match.span() # indexes of the substring found
else:
 print 'IP address not found'
The output will be
IP address found: 192.168.0.1 at position (19, 30)

Monday, May 16, 2011

How to create an Irc echo bot

The example shows how to connect to an irc server and how to read and send data from the server.
import socket

def reply(privmsg, socket):
 """ decode the string with message,
     something like ':nickname!~hostname PRIVMSG my_nickname :hi'
     and echoes the message received to nickname """
 nick = privmsg[1:privmsg.find('!')]
 msg = privmsg[privmsg.find(':',1,len(privmsg))+1:len(privmsg)] 
 socket.send('PRIVMSG '+nick+' :'+msg) # sending to the socket


print 'Connecting...'
s = socket.socket()
s.connect(('irc.freenode.net',6667)) #connection to the irc server
s.send('NICK GlowPy\n')
s.send('USER PythonBot my.host.name humm : My Real Name\n')

while True:
 data = s.recv(1024) # reading from the socket
 print data
 if data.find('PRIVMSG') > 0: # if the string is a message
  reply(data,s)
A conversation with the bot:
<JustGlowing> hi there!
<GlowPy> hi there!
<JustGlowing> how are you?
<GlowPy> how are you?

Friday, May 6, 2011

How to use string's Template

Templates provide simple string substitutions mechanism, here's a simple demonstration:
from string import Template

template = Template('The president of $state is $name')
message = template.substitute(state='USA', name='Obama')
print '1.',message
message = template.substitute(state='France', name='Sarkozy')
print '2.',message

try:
 # will raise an exception
 message = template.substitute(state='England')
except Exception as e:
 print 'I cannot fill the placeholder',e
 #  original name placeholder will be used
 message = template.safe_substitute(state='England') 

print '3.',message
The output of this script will be
1. The president of USA is Obama
2. The president of France is Sarkozy
I cannot fill the placeholder 'name'
3. The president of England is $name