String Manipulation

Bill Mill bill.mill at
Wed Jul 13 17:20:54 CEST 2005

On 13 Jul 2005 07:49:02 -0700, Michael Jordan <golancester at> wrote:
> hey, i have this huge text file and i need to go through and remove all
> punctuation and every instance of the phrase "fruitloops=$" where $ is
> any number 0-100"  um, and yeah this is homework but i've tried to no
> avail.  thanks guys.  cheerio :).  jen


This program iterates through one file and outputs all lines to
another file which have the word "homework" in them.

#-------------------------- Begin program 1
file_in = file('')
file_out = file('data.out')

for line in file_in:
    #line is a string containing one line of the file
    if "homework" in line:
#--------------------------- End program 1

Here is a program which turns a string containing the phrase
"number=42" into a variable containing the integer 42:

#-------------------------- Begin program 2
#create a string variable called x
x = "number=42"

#split the string at the '=', resulting in ['number', '42']
n = x.split('=')[1]

#turn n from a string into a number, so we could test its value
n = int(n)

if 0 < n < 100:
    print "n is between 0 and 100"
    print "n is not between 0 and 100"
#-------------------------- End program 2

And, finally, a program to remove punctuation from a string:

# ------------------------ Begin program 3
import string

#create a sentence with punctuation
punct = "This. is a, sentence with - punctuation"

#remove the punctuation; make sure the first argument
#to maketrans is the same length as the second, which
#should be all blanks
punct = punct.translate(string.maketrans('.,-', '   '))

#read the docs at
# for more details
#------------------------------------End program 3

Hope this helps; you should be able to put the pieces together to do
what you want to do. If you can't, feel free to ask more questions.
Also, just so you know, there is a list at tutor at set up
just to answer questions like these.

Bill Mill
bill.mill at

More information about the Python-list mailing list