Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6016dbe

Browse files
committed
Talk about str() in the discussion of string representations of values, and
give examples for which str() and repr() yield different results. This closes SF bug #485446.
1 parent fa78d0f commit 6016dbe

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

Doc/tut/tut.tex

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2638,11 +2638,34 @@ \section{Fancier Output Formatting \label{formatting}}
26382638
resulting from this formatting operation.
26392639

26402640
One question remains, of course: how do you convert values to strings?
2641-
Luckily, Python has a way to convert any value to a string: pass it to
2642-
the \function{repr()} function, or just write the value between
2643-
reverse quotes (\code{``}). Some examples:
2641+
Luckily, Python has ways to convert any value to a string: pass it to
2642+
the \function{repr()} or \function{str()} functions, or just write
2643+
the value between reverse quotes (\code{``}, equivalent to
2644+
\function{repr()}).
2645+
2646+
The \function{str()} function is meant to return representations of
2647+
values which are fairly human-readable, while \function{repr()} is
2648+
meant to generate representations which can be read by the interpreter
2649+
(or will force a \exception{SyntaxError} if there is not equivalent
2650+
syntax). For objects which don't have a particular representation for
2651+
human consumption, \function{str()} will return the same value as
2652+
\function{repr()}. Many values, such as numbers or structures like
2653+
lists and dictionaries, have the same representation using either
2654+
function. Strings and floating point numbers, in particular, have two
2655+
distinct representations.
2656+
2657+
Some examples:
26442658
26452659
\begin{verbatim}
2660+
>>> s = 'Hello, world.'
2661+
>>> str(s)
2662+
'Hello, world.'
2663+
>>> `s`
2664+
"'Hello, world.'"
2665+
>>> str(0.1)
2666+
'0.1'
2667+
>>> `0.1`
2668+
'0.10000000000000001'
26462669
>>> x = 10 * 3.25
26472670
>>> y = 200 * 200
26482671
>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'

0 commit comments

Comments
 (0)