[Tutor] Two questions [string formatting / str() and repr()]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 1 May 2002 22:29:49 -0700 (PDT)


On Wed, 1 May 2002, Henry Steigerwaldt wrote:

> How can one append different types of variables together and store into
> a variable?
>
> For example, in the Tcl language, one can do the following:
>
> append site_id "$day$ob_time  $wind  $temp/$dwpt  A$pres$equal_sign"
>
> The above example appends to the variable site_id, all the other
> variables located to the right. This piece of code appends different
> types of data together, integers, floats, and characters or strings
> (i.e. the letter A, and the equal sign). And notice that site_id will
> also contain the spaces located between some of the variables.

Hi Henry,


Ah, it looks like you're looking for the "String Formatting" operator.
You can say something like this:

###

## Assuming that 'day', 'ob_time', and the other variables
## are already defined locally:

site_id = "%(day)s%(ob_time)s   %(wind)s  %(temp)s/$dwpt)s " \
          " A$(pres)s%(equal_sign)s"

site_id = site_id % vars()
###


which should do the equivalent to how Tcl concatenates strings.  Here's a
small example:

###
>>> book_name = "The TeXBook"
>>> author = "Knuth"
>>> report = "The book %(book_name)s is written by %(author)s" % vars()
>>> print report
The book The TeXBook is written by Knuth
###



String formatting is particularly well suited to format a string
containing different data types.  The example above opts for strings, but
Formatting will accomodate numeric stuff as well:

###
>>> import math
>>> pi_to_five_places = "%1.5f" % math.pi
>>> print pi_to_five_places
3.14159
>>> pi_to_ten_places = "%1.10f" % math.pi
>>> pi_to_ten_places
'3.1415926536'
###


You can find out more about String Formatting in the Python Tutorial:

    http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000

and for the gruesome details, the library reference docs will oblige:

    http://www.python.org/doc/current/lib/typesseq-strings.html





> There is a string.join function in Python, but this is used only to join
> different "strings" together. I cannot however find an example of how to
> combine different data forms together (strings, integers, floats, etc.)
> like my example above does in Tcl.

string.join() will also work as an alternative, although it involves extra
steps to turn things into strings.  I think that for your case, String
Formatting is an effective way to go.  Still, it might be good to see how
we might manage with string concatenation.


###
>>> 42 + " is the answer"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'int' and 'str'
>>> str(42) + " is the answer"
'42 is the answer'
>>> `42` + " is the answer"
'42 is the answer'
###




[Subtle point ahead; ignore when it gets boring.  *grin*]

The last example, the one using backquotes, uses shorthand for the repr()
function:

###
>>> repr(42) + " is the answer"
'42 is the answer'
###

The repr() function is almost like str(), except that repr() is the
function that Python uses to "repr"esent data so that we can detect its
type.  Let's compare the two functions for a moment:

###
>>> print str("I am a string")
I am a string
>>> print repr("I am a string")
'I am a string'
###

Note that in the second case, repr() puts quotes around the string, to
tell us that it's a string.  repr() puts out a string representation that
can be directly typed into the interactive interpreter, to get that same
value.

repr() can give small visual hints and is useful when doing debugging.
Don't worry too much about it: usually, str() is what you want.
http://python.org/doc/current/lib/built-in-funcs.html explains the
definition of repr() in more detail.




Anyway, hope this helps.  Please feel free to ask more questions.  Good
luck to you!