HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

is there a better way than replace to write this function?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisthanreplacewaybetterwritefunctionthere

Problem

I am doing my homework and i have done this? Is there any other better way to do this?

def write_log(name, total):
    # change user input with shape names
    name = name.replace('1', 'triangle')
    name = name.replace('2', 'square')
    name = name.replace('3', 'rectangle')
    name = name.replace('4', 'pentagon')
    name = name.replace('5', 'hexagon')
    name = name.replace('6', 'octagon')
    name = name.replace('7', 'circle')

    total = int(total)

    logfile = open("text.txt", "a")

    if (total == 1):
       towrite = ('%i %s \n'
                  % (total, name))

    elif (total >= 2 and total <= 5):
       name += 's' # add s to name to make it plural
       towrite = ('%i %s \n'
                  % (total, name))
    else:
       towrite = ''
    try:
       logfile.write(towrite)
    finally:
       logfile.close()
    return

Solution

-- One --

You can use a dictionary to hold your translation data:

mydict = {'1':'triangle', '2':'square', '3':'rectangle',
          '4':'pentagon','5':'hexagon', '6':'octagon','7':'circle'}


Now your list of replacement lines becomes simply:

for key, value in mydict.iteritems():
    name = name.replace(key, value)


another option would be:

for key in mydict:
    name = name.replace(key, mydict[key])


To make this part complete, consider also a tuple for holding your data as indicated in @larmans answer. See also comments in the answers. I think there are interesting hints about which could be the best alternative for different cases.

-- Two --

also remember you can do

2 <= total <= 5


instead of

total >= 2 and total <= 5


-- Three --

Note you dont need parenthesis in the if expressions. Just do this:

if total == 1:

Code Snippets

mydict = {'1':'triangle', '2':'square', '3':'rectangle',
          '4':'pentagon','5':'hexagon', '6':'octagon','7':'circle'}
for key, value in mydict.iteritems():
    name = name.replace(key, value)
for key in mydict:
    name = name.replace(key, mydict[key])
2 <= total <= 5
total >= 2 and total <= 5

Context

StackExchange Code Review Q#7857, answer score: 7

Revisions (0)

No revisions yet.