[Tutor] some string operations
Reed O'Brien
reed at reedobrien.com
Sat Oct 4 10:27:08 CEST 2008
On Oct 4, 2008, at 4:03 AM, David wrote:
> Dear list,
>
> one of the exercises in Zelle's book is:
>
> given
>
> import string
> s1 = "spam"
> s2 = "ni!"
>
> show a Python expression that could construct the following result
> by performing string operations on s1 and s2:
>
> "Spam Ni! Spam Ni! Spam Ni!".
>
> I have two solutions:
>
> a)
> (string.capitalize(s1) + " " + string.capitalize( s2) + " " ) * 3
>
> b)
> "%s %s " % (string.capitalize(s1), string.capitalize(s2)) * 3
>
> Both seem to work, but they seem overly complex. Where could I
> improve?
>
> Also, Python returns:
>
> 'Spam Ni! Spam Ni! Spam Ni! '
>
> Which is not exactly "Spam Ni! Spam Ni! Spam Ni!" (note the final
> free space in my outcome). I am at a loss as to how to perfect my
> answer with regard to this issue.
>>> s1, s2 = 'spam', 'ni!'
>>> ' '.join([s.capitalize() for s in (s1, s2)] * 3)
'Spam Ni! Spam Ni! Spam Ni!'
HTH,
~ro
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2421 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20081004/dadc1b6b/attachment-0001.bin>
More information about the Tutor
mailing list