snippsat 661 Master Poster

Dont use variable name as sum and file,these word are use by python.
So my_file is ok because it not used by python an give a NameError.

>>> sum
<built-in function sum>
>>> file
<type 'file'>
>>> my_file
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'my_file' is not defined

count() as used over is ok to use for a word as "Olympics".
But to count other word,it can act not as expected.
If i want to count word "hi" that occurred 1 time in variable s i get 4.

>>> s = 'hi is hirohito in japan,higher or lower'
>>> s.count('hi')
4

There are several way to solve this,split() and using collections.Counter can be one nice way.

>>> from collections import Counter
>>> s = 'hi is hirohito in japan,higher or lower'
>>> s = s.split()
>>> c = Counter(s)
>>> c['hi']
1
snippsat 661 Master Poster
snippsat 661 Master Poster

How do you make Python delete a string or a number (in this case, .0) from a file? Example:

Here many think about this in a wrong way.
The way you do is not deleting from orgnial file.

You do changes that is needed and then you write result to a new file.
This way you have orginal file intact and a new file with desired result.
If needed you can rename new file to orginal file name.

Pyhon has file fileinput module that can do changes to orginal file.
Behind the scenes(it dos what i describe over),fileinput creates a temp file and directs print() to the temp file,
then when you are done writing.
Fileinput deletes the original file and renames the temp file.

An example.
Here i want to remove/delete "line2 cat".

afile.txt-->
line 1 dog
line 2 cat
line 3 monkey

Here you see that "new_file.txt" has the desired resul and "afile.txt" is still intact.

    with open('afile.txt') as f, open('new_file.txt', 'w') as f_out:
        for line in f:
            if not 'cat' in line:
                f_out.write(line)

'''Output-->
line 1 dog
line 3 monkey
'''
snippsat 661 Master Poster

The best way is to always use raw string(r) when give path in windows.
There is also an option to use \\ or /.

So this do not work.
os.chdir('C:\test')
This work.

os.chdir(r'C:\test')
os.chdir('C:\\test')
os.chdir('C:/test')

The reason why is this way,is that a singel backslashes(\) in python can(do) get read as an escape character.
@sepp2k also metion that you need escape your backslashes.
Take a look at this.

>>> s = 'C:\test'
>>> print s
C:  est
>>> print repr(s)
'C:\test'
>>> repr(s)
"'C:\\test'"

Then with raw string.

>>> s = r'C:\test'
>>> print s
C:\test
>>> print repr(s)
'C:\\test'
>>> repr(s)
"'C:\\\\test'"

One more \

>>> s = 'C:\\test'
>>> print s
C:\test
snippsat 661 Master Poster

You are getting the memory adress of object.

class Foo(object):
    def bar(self):
        return 'Hello'

Test class.

>>> obj = Foo()
>>> print obj
<__main__.Foo object at 0x0356B110>
>>> print obj.bar
<bound method Foo.bar of <__main__.Foo object at 0x0356B110>>
>>> print obj.bar()
Hello

As you see until a make correct call i get memory adress of object at 0x......
You can try something like index(), index.method_name, index.method_name().

snippsat 661 Master Poster

Or shorten ZZucker function down to this.
All you need to know if it`s True or False.

def palindrome(mystr):
    return mystr.lower() == mystr[::-1].lower()

mystr = "racecar"
print palindrome(mystr)
snippsat 661 Master Poster

What is the most Pythonic way?

Not to typecheck.
Need to know the type of an object?
Let me make a brief argument: No, you don't.
Just use the object as if it was whatever you expect it to be, and handle any errors that result.
http://www.siafoo.net/article/56

@S.Lott
Actually, a manual type check in Python is almost always a waste of time and code.
It's simply a bad practice to write type checking code in Python.
If an inappropriate type was used by some malicious sociopath, Python's ordinary methods will raise an ordinary exception when the type fails to be appropriate.
You write no code, your program still fails with a TypeError.
There are very rare cases when you must determine type at run-time.

snippsat 661 Master Poster

I only use BeautifulSoup or lxml,because they are by far the two best parser for python.
Can show you on way with BeautifulSoup.
soup.find_all('router') find all ruter tag,i take out router 1 router_tag[0]
Then put id and ip text in a dictionary.

from bs4 import BeautifulSoup

xml_file = """\
<routingTable>
    <router>
        <id>1</id>
        <ip>1.1.1.1</ip>
        <nexthop>1.1.1.2</nexthop>
    </router>
    <router>
        <id>2</id>
        <ip>2.2.2.1</ip>
        <nexthop>2.2.2.2</nexthop>
    </router>
</routingTable>"""

router1_dict = {}
soup = BeautifulSoup(xml_file, 'xml')
router_tag = soup.find_all('router')
router_1 = router_tag[0]
router1_dict[router_1.find('id').text] = router_1.find('ip').text
print router1_dict #--> {u'1': u'1.1.1.1'}
Gribouillis commented: thanks +13
snippsat 661 Master Poster

I did not guess the right answer.
I did now that that exec "print(a+b)" evaluate to 7 and that dict(a=6, b=9) make a dictionary.
So False was my guess because 7 in not in that dictionary,and only 'a' and 'b' would return True.
I did probably know that this was the wrong guess and that there where a catch.

So i looked into it and my understaning of this is.

>>> a = 2
>>> b = 5
>>> globals()
{'a': 2, 'b': 5, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}}

So when exec "print(a+b)" run it look into globals() and find that a is 2 and b is 5.
Then evaluate that and output 7.

But when we use exec with in,exec dos not look into globals(),
but it look into the given dictionary.
There it find that a is 6 and b is 9 and we get output of 15 wish is the correct answer.
Feel free to correct me if something i sad is wrong.

snippsat 661 Master Poster
from bs4 import BeautifulSoup

html = """\
<html>
<head>
   <title>html page</title>
</head>
<body>
  <div>Hello world</div>
</body>
</html>
"""

soup = BeautifulSoup(html)
head_tag = soup.find('head')
head_tag.name = 'New name'
print soup.prettify()

"""Output-->
<html>
 <New name>
  <title>
   html page
  </title>
 </New name>
 <body>
  <div>
   Hello world
  </div>
 </body>
</html>
"""
snippsat 661 Master Poster

Komodo Edit there is a little more stuggle to setup run button.
http://community.activestate.com/forum-topic/executing-python-code-within-komodo-edit
Komodo IDE has run button build in,because it has debugging features for python build in.

Look at Pyscripter(windows only) and Spyder great editors for python.
Can also mention Pydev wish is powerful,not as lightweigt need of course to install Eclipse.

Gribouillis commented: good pointers +13
snippsat 661 Master Poster

What, so I use C# or something?

What is so hard to understand?,you can not use any language in all universe.
When you say creating a new script language it dos not excits.

Before python,C#,javascript was created they did not excits.
You can of course use theese languages to write stuff like a lexer,parser.
But when that is done your new language has to interpreter/compile all on it`s own.
If it use interpreter/compiler from other languages is not a new language.

As you can see, I have made a sort of scripting language :P

No no.
What you doing here is just to use feature of a languages to solve a specific task.
Also just what ordinary programming is all about.
It`s not a new script language because if you do not use javascript your program can not run.

snippsat 661 Master Poster

I dont know why but extend adds 'devide' as another list to oper

No.

I couldn't find "extend" function for lists

Have you even looked?
Help from interactive interpeter.

>>> help(oper.extend)
Help on built-in function extend:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable

The keyword here is iterable.
Here is an other one with extend,this one is harder to guess and is it possible to guess exact output?

l = [1, 2, 3]
d = {4: 5, 6: 7, 8: 9}
l.extend(d)
print l #?
snippsat 661 Master Poster

There are a couple thing i want to clear up.
Just to make it very clear when you say a new scripting language.
This mean that you have to close python and not use python at all.

Then with the new language you can do something like this.

>>> print 'hello world'
hello world
>>> 2 + 2
4

This is not so easy as it look.

Which allows the user to script some sort of functionality?

Yes python can do a lot stuff,and this is no problem.
But i think bye you saying creating a new scripting language you create confusion
because creating a new language is a very diffcult task.
And i'm not sure that is your task.

snippsat 661 Master Poster

There is no need to use split(' ') Lucaci,just use split().
split() always splits on all whitespace if left unspecified.

snippsat 661 Master Poster

A little help or mayby to much.

>>> s = "This is it!".split()
>>> s
['This', 'is', 'it!']
>>> len(s[0])
4
>>> [len(i) for i in s]
[4, 2, 3]

Try to figure out what happens in code over.
And as a practise [len(i) for i in s] write this line as a basic for loop with append as pyTony suggest.
This line called list comprehesion and are very common to use in python,so it good to look into it even if you have just start learing python.

snippsat 661 Master Poster

I change the code little,to how i think it should look.
Ask if you dont understand it.

def average(a,b,c):
    avr = (a+b+c) / 3.0
    return avr

def main():
    user_input = input("Please enter any three numbers: ")
    numbers = [float(i) for i in user_input]
    avr = average(numbers[0],numbers[1],numbers[2])
    print('The average of these numbers = {}'.format(avr))

main()
snippsat 661 Master Poster

Now you just using python,you can not just use features of python and say it`s a new script language.

A new language in beginning has to understand how to read integer,string.
You have to write a lexer,parser and more stuff to get it to work.
http://www.flipcode.com/archives/Implementing_A_Scripting_Engine-Part_1_Overview.shtml

snippsat 661 Master Poster

a,b are are really bad variable names.
It`s ok to use only in small code examples,should not be used in finish scripts.
if b in i really easy to understand?
Bare except: should not be used.
I explain better why not in this post.
http://www.daniweb.com/software-development/python/threads/423971/python-program-detect-if-files-exist#post1812471
There is no need to use found 0 and 1.

So a more pythonic version would look like this.

def find():
    file_in = raw_input("Insert file: ")
    pattern = raw_input("Insert pattern: ")
    try:
        with open(file_in) as a_file:
            for file_content in a_file:
                if pattern in file_content:
                    return 'Pattern was found'
                return 'Pattern was not found'
    except IOError:
        return "Invalid file."

print find()
snippsat 661 Master Poster

Is it possible to create a scripting language using Python?

Yes,but why?

Your script show that you have very much to learn before thinking about writing an other language in python.
An postet over now code is almost a joke with infinite recursion,do you know what this mean?
Programming language design concepts should be study for a long time before trying to make something useful.

snippsat 661 Master Poster

abhilam we have answered you in this post.
http://www.daniweb.com/software-development/python/threads/425088/reading-a-column-from-text#post1817281
Why do you post same question in this two year old thread(marked solved)?,this is not good at all.

snippsat 661 Master Poster

Another way to get the same result you can look at.

flag = 1
with open('over.txt') as f, open('output', 'w') as f_out:
    for line in f:
        if line.startswith('  Panicle'):
            flag = 0
        if not flag:
            f_out.write(line[-19:])
snippsat 661 Master Poster
>>> s = 'hi my name is bill'
>>> ''.join(s.split())
'himynameisbill'
>>> list(''.join(s.split()))
['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'b', 'i', 'l', 'l']
snippsat 661 Master Poster

Something like this?

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)

        #--Panel so it look good on all platforms
        self.panel = wx.Panel(self)
        self.datepick = wx.DatePickerCtrl(self.panel,-1, pos=(20,15),
                              style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY)
        self.datepick.Bind(wx.EVT_DATE_CHANGED, self.onAction)
        self.label = wx.StaticText(self.panel,-1,"", pos=(20,50))

    def onAction(self, event):
        '''Process data from picked date'''
        selected = self.datepick.GetValue()
        month = selected.Month + 1
        day = selected.Day
        year = selected.Year
        date_str = "%02d/%02d/%4d" % (month, day, year)
        self.label.SetLabel("Date selected = {}".format(date_str))

app = wx.App()
MyFrame(None, 'DatePickerCtrl', (350, 240)).Show()
app.MainLoop()
snippsat 661 Master Poster

Nice to use with, not sure when it was introduced?

In python 2.5 september 19, 2006.

Bare "except:", with no exception specified is nasty because it can easily hide bugs.

except: #Dont do this

To use your code as example.

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = ope(filename) # misspelled "open"
        f.close()
        return True
    except:
        return False 

print file_exists('somefile.txt')

The misspelled "open" triggers a NameError,which is caught by the except clause.
So funcion return False,so it hide the real problem that there is NameError.
except IOError will only catch IOError and show that NameError is the problem.

When people see bare "except:" in code they can complain about it.
http://python.6.n6.nabble.com/issue4788-two-bare-quot-except-quot-clauses-are-used-in-the-ssl-module-td701941.html

Gribouillis commented: I totally agree +13
snippsat 661 Master Poster

HiHe function is ok,but some changes that i think make it better.
Bare except(catch all maybe) i dont like this to much.
And with open() is preferred over open(),no need to close file object and it dos some error checking to.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

Or return the specific error masseage to user.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError as error:
        return 'A problem occurred: {}'.format(error)
snippsat 661 Master Poster

Look at os.path.exists and os.path.isfile thats dos what you describe.

>>> help(os.path.exists)
Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

>>> help(os.path.isfile)
Help on function isfile in module genericpath:

isfile(path)
    Test whether a path is a regular file

Or try/except that is a safe an pythonic way to solve this.

try:
   open()
except IOError as e:
   print 'No file found'
snippsat 661 Master Poster

or how would you change it (or may be some part of it) to looks it more elegant and to be more efficient.

here is the code:

You are making 88 random numbers in range 0 to 9 and want to count occurrence.
use randint() because it are bettter suited for this than choice().
In python 2.7--> collections.Counter is nice

>>> from collections import Counter
>>> from random import randint
>>> print Counter([randint(0,9) for i in range(88)])
Counter({7: 12, 1: 11, 3: 10, 8: 10, 9: 10, 0: 9, 2: 7, 4: 7, 5: 7, 6: 5})

So you see it dos the same,or maybe if i do this you see it clearer.

from collections import Counter
from random import randint

runs = 88
numbers = Counter(randint(0,9) for i in range(runs))
for numb in numbers:
    print 'Number {0} occurred {1}'.format(numb, numbers[numb])

'''Output-->
Number 0 occurred 4
Number 1 occurred 7
Number 2 occurred 13
Number 3 occurred 10
Number 4 occurred 5
Number 5 occurred 10
Number 6 occurred 10
Number 7 occurred 11
Number 8 occurred 10
Number 9 occurred 8
'''

Before python 2.7 and still is using dictionary a common way to count stuff.

>>> d = {}
>>> numbers = [randint(0,9) for i in range(88)]
>>> for v in numbers: d[v] = d.get(v, 0) + 1
>>> print d
{0: 4, 1: 11, 2: 10, 3: 4, 4: 13, 5: 8, 6: 12, 7: 7, 8: 11, …
Gribouillis commented: good help +13
snippsat 661 Master Poster

The tutorial about BeautifulSoup is not so good.
The use of regex is not needed,let BeautifulSoup do the job.
Regex with html is not so good,you can mix in regex some time to do a little cleaning.
But here it`s not needed.

To get all picture from this link.

from BeautifulSoup import BeautifulSoup
import urllib2

url = urllib2.urlopen('http://supertalk.superfuture.com/index.php?/topic/95817-2-for-1-pics/page__st__500')
soup = BeautifulSoup(url)
links = soup.findAll('img', src=True)
for link in links:
    print link['src']

Why is regex not good with html/xml?,i usually post this link.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

snippsat 661 Master Poster

Using re.split() is also and option.

>>> import re
>>> s = '1--2--3--4---5---6--7---8'
>>> re.split(r'\-+', s)
['1', '2', '3', '4', '5', '6', '7', '8']
TrustyTony commented: True +12
vegaseat commented: nicely done +14
snippsat 661 Master Poster

itertools.product will also do this.

import itertools
import pprint

letters = ['A', 'B', 'C']
pprint.pprint(list(itertools.product(letters, repeat=3)))

"""Output-->
[('A', 'A', 'A'),
 ('A', 'A', 'B'),
 ('A', 'A', 'C'),
 ('A', 'B', 'A'),
 ('A', 'B', 'B'),
 ('A', 'B', 'C'),
 ('A', 'C', 'A'),
 ('A', 'C', 'B'),
 ('A', 'C', 'C'),
 ('B', 'A', 'A'),
 ('B', 'A', 'B'),
 ('B', 'A', 'C'),
 ('B', 'B', 'A'),
 ('B', 'B', 'B'),
 ('B', 'B', 'C'),
 ('B', 'C', 'A'),
 ('B', 'C', 'B'),
 ('B', 'C', 'C'),
 ('C', 'A', 'A'),
 ('C', 'A', 'B'),
 ('C', 'A', 'C'),
 ('C', 'B', 'A'),
 ('C', 'B', 'B'),
 ('C', 'B', 'C'),
 ('C', 'C', 'A'),
 ('C', 'C', 'B'),
 ('C', 'C', 'C')]
 """
snippsat 661 Master Poster

Use code tag so indentation works.
You are doing some unnecessary stuff.
The answer is not so long,so i dont break it up.

with open('age.txt') as f:
    for item in f:
        sorted_list = sorted(item.split(','), key=int)

with open('age_out.txt', 'w') as f_out:
    f_out.write(','.join(sorted_list))
    #--> 12, 13, 14, 15, 16, 17, 18, 19, 20

Some point is best to always use with open(),then you dont need to close fileobject.
And with open() is doing some error handling to.
When you read from file and write to file it is string that is used.
Here i dont convert the list to integer and sort,but use key=int to sort the list of string.
Then join that list to a string and write to file.

TrustyTony commented: Elegant one! +12
snippsat 661 Master Poster

Dont use array,in python we call it list.
import array is only for very specialized task.

Your indentation is wrong and you read in file more than once.
Take a look at this,and you should read a basic tutorial about list in python.

numb_list = []    
with open('numb.txt') as f:
    for item in f:
        numb_list.append([int(i) for i in item.split()])

print numb_list
print numb_list[0]  #print list
print 'A number in list 0: %d' % numb_list[0][2]

"""Output-->
[[1, 4, 5, 3], [1, 0, 2, 4, 18], [5, 2, 0, 0, 9]]
[1, 4, 5, 3]
A number in list 0: 5
"""
snippsat 661 Master Poster

You can try binarie install from this site.
http://www.voidspace.org.uk/python/modules.shtml#pycrypto

snippsat 661 Master Poster

Does first alternative not work in Python 3?

No,in python 3 print is a function.

Read about diffrence.
http://diveintopython3.ep.io/porting-code-to-python-3-with-2to3.html

snippsat 661 Master Poster

You need to post your code with Traceback error.
We can not help by guessing how code look.

spyder 2.1.9 Setup

Python 2.7 is not installed on your computer

OK

Install 2.7.
http://packages.ubuntu.com/oneiric/python-spyderlib

snippsat 661 Master Poster

There is no error i code you posted.
Post code with Traceback you get.

so python use ## This is the example of the code. and so on like any

Yes you can use 1 # or two ##..,to make comments in code.

Now from these two programs "Notepad++" and "EditPlus Text Editor"
which one is the best to edit and rewrite python files?

Using a IDE editor like Pyscripter or Spyder will help you more.
These editors will mark out error like SyntaxError in code.

snippsat 661 Master Poster

Or like this.

>>> [float(numb[0]) for item in alist for numb in item]
[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]   

If i break up list comprehension up it can be eaiser du understand what`s going on.

>>> alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]]
>>> numb_list = []
>>> for item in alist:
        for numb in item:
            numb_list.append(float(numb[0]))    

>>> numb_list
[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]
snippsat 661 Master Poster

Pyscripter as mention is great(windows only)
I will also mention Spyder 2 and Pydev

snippsat 661 Master Poster

This will do it,run script in same folder as pdf1,pdf2...
Output will be project 1, project 2...
Be aware that this will rename all pdfs in folder that you run script in.

import os
import glob

for numb, name in enumerate(glob.glob('*pdf'), 1):
    #print numb, name #test
    os.rename(name, 'project %s.pdf' % numb)
snippsat 661 Master Poster

Because all I need to do is scan the entire drive (C: as it would be in this case) for any file matching the .xyz extension, and create a list of all found files.

In basic something like this.

import os

file_list = []
for root, dirs, files in os.walk(r'C:\test'):
    for f_name in files:
        if f_name.endswith('.py'):
            file_list.append(f_name)

print(file_list)

If needed also path to files.

import os

file_list = []
for root, dirs, files in os.walk(r'C:\test'):
    for f_name in files:
        file_path = os.path.join(root, f_name)
        if file_path.endswith('.py'):
            file_list.append(file_path)

print(file_list)

endswith() can take a tuple for more than one extension endswith(('.py', '.jpg'))

snippsat 661 Master Poster

Where is sticky treads starting python,Gui programming....?
These were very good treads and should be sticky.

snippsat 661 Master Poster

Code are sending shellcode through a socket with python code.

Shellcode is a piece of machine-readable code, or script code that has just one mission; to
open up a command interpreter (shell) on the target system so that an “attacker” can type in
commands in the same fashion as a regular authorized user or system administrator of that
system can do (with a few not-so-important exceptions of course).

Shellcode is primarily used to exploit buffer overflows (including heap overflows) or format
string bugs in binary, machine-readable software.

snippsat 661 Master Poster

Hmm that type-checking is from outer space.
You should not use vars() . vars() or locals(),globals() provides low level access to variables created by python.
Dont use python internal working in your code.

To check for integer or float here a couple of way.
Here you only get out of loop if input is a integer or float.

while True:
    try:
        number = float(input('Enter a number: '))
        print('val correct %s' % number)
        break
    except ValueError:
        print('Please only numbers,try again')

type() is not good to use,we can use isinstance() instead.

l = [1, 2.5, 'a']

for item in l:
      if isinstance(item, (int,float)):
          print('%s is a number' % item)
      else:
        print('%s is not number' % item)

"""Otuput-->
1 is a number
2.5 is a number
a is not number
"""

Type-checking in python is something that not so popular.

Need to know the type of an object? Let me make a brief argument: No, you don't.
Just use the object as if it was whatever you expect it to be, and handle any errors that result.

snippsat 661 Master Poster

I wonder about the same as woooee.
Using a parser can be better for this task as BeautifulSoup or lxml.
A quick demo.

from BeautifulSoup import BeautifulStoneSoup

xml = '''\
<tag>
<number>1</number>
<info>blah blah</info>
<more>Lorem Ipsum</more>
<anothertag>The quick brown fox...</anothertag>
<id>32444</id>
<yetmore>blah blah</yetmore>
</tag>
<tag>
<number>2</number>
<info>qwerty</info>
<more>yada yada qwerty</more>
<anothertag>yada yada qwerty</anothertag>
<id>32344</id>
<yetmore>yada yada qwerty</yetmore>
</tag>
<tag>
<number>3</number>
<info>yada yada qwerty</info>
<more>yada yada qwerty</more>
<anothertag>yada yada</anothertag>
<whatever>yada</whatever>
<id>32444</id>
<yetmore>yada yada</yetmore>
</tag>'''

soup = BeautifulStoneSoup(xml)
tag = soup.findAll('id')
print tag
#--> [<id>32444</id>, <id>32344</id>, <id>32444</id>]
snippsat 661 Master Poster

You have a post with same question.
http://www.daniweb.com/software-development/python/threads/416862

In this post you give more info about html file.
What you post now is just a mess,read about function.
Is this a school task? can you use regex in this task?

import re

info = '''<table>
    <tr align = "center">
        <h1> Lachlan Osborn </h1>
        <p> Address: 5 Smith Street, Manly <br>
        Date of Birth: 26th April 1993 </p>

        <a href="semester.html"><b>My Semester Units</b></a>
        <p><b>Check out my <a href="hobbies.html">hobbies.</a></b></p>
    </tr>
</center>'''

def remove_html(info):
    text = re.sub(r'<.*?>', '', info)
    text = text.strip()
    text = text.replace('\n\n', '\n')
    for line in text.split('\n'):
        print line.strip()

remove_html(info)
"""Output-->
Lachlan Osborn
Address: 5 Smith Street, Manly
Date of Birth: 26th April 1993
My Semester Units
Check out my hobbies
"""
snippsat 661 Master Poster

For example, a text file that shows: <title>Lachlan Osborn</title>
and the output should be like that: Lachlan Osborn

It can dependent how that text file look.
Can cange regex to something like this.

import re

data = '''\
<title>Lachlan Osborn</title>
<head>hello world</head>
'''

text = re.sub(r'<.*?>', '', data)
print text.strip()
"""Output-->
Lachlan Osborn
hello world
"""
snippsat 661 Master Poster

By the way, you may want to look at the BeautifulSoup Python library for working with html files (and extracting text from them).

I agree with this,but now it look like boiishuvo will destroy the stucture of html.
Should it replace like this or keep <> intact?

>>> s = '<html>'
>>> s.replace('<html>', '***')
'***'

Something like this with regex.

import re

html = '''\
<html>
<head>
    <title></title>
</head>
<body>

</body>
</html>'''

print re.sub(r'<.*>', '****', html)
"""Output-->
****
****
    ****
****
****

****
****
"""
snippsat 661 Master Poster

A little more about this. is is the identity comparison. == is the equality comparison.

With id() we can se memory loaction.
So here a and b point to same place in memory.

>>> a = 5
>>> b = 5
>>> a is b
True
>>> id(a)
4062136
>>> id(b)
4062136

Let`s try with list.

>>> a = []
>>> b = []
>>> a is b
False
>>> a == b
True
>>> id(a)
41004848
>>> id(b)
41004968

People often think that is is part of the comparison operator set.
The is statement does not compare two objects.

So a good rule is to not use is unless you want to check if something is None or something is not None.
The reason is works for things like "a is None" is because there is
only one None builtin in memory ever.

HiHe commented: good explanation +5
snippsat 661 Master Poster

If we mix together what you have it can look like this.

def firstLetter(s):
    '''Count first letter in a sentence'''
    place = {}
    for item in s.lower().split():
        place[item[0]] = place.get(item[0], 0) + 1
    return place

s = "Today is tomorrow"
print firstLetter(s)
#--> {'i': 1, 't': 2}
help(firstLetter) #Look at this to se docstring work

A little more you can look at.

>>> s = "Today is tomorrow"
>>> [lett[0] for lett in s.lower().split()]
['t', 'i', 't']

list comprehension as i use here is much used in python.
As you a simpe way to get first letter.
From python 2.7--> we can use Collections.counter to count stuff.

>>> from collections import Counter
>>> s = "Today is tomorrow"
>>> Counter(lett[0] for lett in s.lower().split())
Counter({'t': 2, 'i': 1})