removing spaces when mixing variables / text

Dang Griffith noemail at noemail4u.com
Tue Feb 3 14:10:55 CET 2004


On Tue, 03 Feb 2004 02:14:18 -0600, "tgiles" <tgiles at spam.kc.rr.com>
wrote:

>Ok, I started playing around with random() and decided to write a script
>to generate random dotted quad IP addresses, just to see if I could do it.
>
>Everything is perfect with the glaring exeception of the output. It seems
>as if when one uses the "," in a print statement, you get an empty space
>in between variables and what I want there (namely, the ".").
Mike pointed out one a common idioms that includes a couple of idioms.
To customize it for random IP addresses:

'.'.join([str(random.randint(0,255)) for i in range(4)])

The two idioms are using the string join method to build a single
string from small parts, connecting with a single value.

The other idiom is a list comprehension.  In a list comprehension, you
combine an expression and a loop, sometimes with a condition.  In this
example, the expression str(random.randint(0,255)) is independent of
the loop itself.  The loop is used to iterate 4 times.  I suppose
using range(4) to iterate 4 times could be considered an idiom also.

    --dang



More information about the Python-list mailing list