[Tutor] String Replacement question

Moishy Gluck moishyyehuda at gmail.com
Wed May 21 13:04:16 CEST 2008


Some other solutions might be

>>> animal = 'cat'
>>> " ".join((animal, ) * 4)
'cat cat cat cat'
>>> animal = 'cat'
>>> print " ".join((animal, ) * 4)
cat cat cat cat
>>>#If you need the string injected into another string
>>> print "My %s's name is ginger." % (" ".join((animal,) * 4))
My cat cat cat cat's name is ginger.
>>>

On Wed, May 21, 2008 at 6:36 AM, Kent Johnson <kent37 at tds.net> wrote:

> On Wed, May 21, 2008 at 5:35 AM, Faheem <faheem at atlantiscomputing.com>
> wrote:
> > Hi all,
> >  How do I replace the same value multiple times without repeating the
> > same variable name/value repeatedly?
> > for ex.
> >
> >  some = 'thing'
> >  print '%s %s %s %s' % (some,some,some,some)
>
> You can use named parameters, which moves the repetition to the format
> string:
>
> In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some))
> thing thing thing thing
>
> With multiple values, a common trick is to pass vars() or locals() as
> the dict, giving the format access to all defined variables:
>
> In [27]: a=1
>
> In [28]: b=2
>
> In [29]: print '%(a)s %(b)s' % vars()
> 1 2
>
> If you literally need to repeat as in your example, you could do this:
>
> In [26]: print '%s %s %s %s' % (4*(some,))
> thing thing thing thing
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080521/4ac3ef9d/attachment.htm>


More information about the Tutor mailing list