newbie question: getting rid of space in string :(

Mark McEahern marklists at mceahern.com
Fri Jul 12 12:14:25 EDT 2002


Joseph, as someone else has pointed out, the comma at the end of print foo,
is responsible for the space.  You have at least two options:

  o print things all at once

    l = []
    for x in "foobar":
      l.append(x)
    print ''.join(l)

  o write to sys.stdout

    import sys
    for x in "foobar":
      sys.stdout.write(x)

The following modification of your script allows you to explore several
interesting ideas in Python:

  o generators
  o nested scopes
  o the use of locals() to add simplicity and clarity to format strings
  o use lists to accumulate strings before printing
  o string methods (e.g., join)
  o the fact that you should never name a variable to conflict with the name
of a module in the standard library (e.g., string, i renamed to 's')

Cheers,

// mark

#! /usr/bin/env python

from __future__ import generators

def make_color_switch(color1, color2):
    def color_switch():
        i = 0
        while True:
            if i % 2:
                yield color2
            else:
                yield color1
            i += 1
    return color_switch

def colorize(s, color1, color2):
    color_switch = make_color_switch(color1, color2)()
    template = "<%(color)s><b>%(c)s</b></color>"
    l = []
    for c in s:
        color = color_switch.next()
        l.append(template % locals())
    print ''.join(l)

colorize("testing", "black", "red")

-----Original Message-----
From: python-list-admin at python.org [mailto:python-list-admin at python.org]On
Behalf Of Joseph Youssef
Sent: Friday, July 12, 2002 12:53 AM
To: python-list at python.org
Subject: newbie question: getting rid of space in string :(


Hello, I'm new to python and I'm writing a very small script which takes
each letter of a string and adds text to it (I know this is not a good
explanation but you'll understand below :) )

anyway, this is my current code:

def textColor(string, color1, color2):
    color = color1
    for a in string:
        print "<" +color+ "><b>" +a+ "</b></" +color+ ">",
        if color == color1:
            color = color2
        else:
            color = color1


so when I run let's say textColor("testing","black","red")
it returns:
<black><b>t</b></black> <red><b>e</b></red> <black><b>s</b></black>
<red><b>t</b></red> <black><b>i</b></black> <red><b>n</b></red>
<black><b>g</b></black>

now this works just fine exept that space in between each block of text, I
can't get it to stick together, now I know this is a very easy question but
I need some quick help

thanks







--
Too often we lose sight of life's simple pleasures. Remember when someone
annoys you it takes 42 muscles in your face to frown, BUT, it only takes 4
muscles to extend your arm and bitch-slap that mother@#?!&! upside the head!

-






More information about the Python-list mailing list