Beginner Python RE Question: String Formatting Type and repr () Function

So, I have this code:

formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") 

And I get this output:

1 2 3 4

'one' 'two' 'three' 'four'


My question is:

Why are there single quotes in the second line of output? I'm not quite sure how the% r conversion type really works.

When I change the code to:

 formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print "%s %s %s %s" % ("one", "two", "three", "four") 

I get this result:

1 2 3 4

one two three four

I just don’t understand why they work differently. Can someone break me for me?


I read:

http://docs.python.org/library/stdtypes.html &

http://docs.python.org/library/functions.html#repr

+4
source share
2 answers

With the expression 'abc%rdef' % obj part '%r' is replaced with repr(obj)

With the expression 'ABC%sDEF' % obj part '%s' is replaced with str(obj)

.

repr () is a function that, for ordinary objects, returns a string that matches the one you must write to the script to determine the object passed as repr () argument:

For many types, this function tries to return a string that will give an object with the same value when passed to eval () http://docs.python.org/library/functions.html#repr

.

Example 1

if you consider the list defined by li = [12,45,'haze']

print li will print [12,45, 'haze']

print repr(li) also print [12,45, 'haze'] because [12,45,'haze'] is a sequence of characters written in a script to define a list li with this value

Example 2

if you consider the string defined by ss = 'oregon' :

print ss will print oregon without quotes around

print repr(ss) will print 'oregon', since 'oregon' is a sequence of characters that you must write to the script if you want to define an ss string with the value oregon in the program

.

Thus, this means that in fact for common objects, repr () and str () return strings that are generally equal, with the exception of a string object. This makes repr () especially interesting for string objects. It is very useful to parse the contents of HTML codes, for example.

+2
source

%s tell python to call the str() function for each element of your tuple. %r tell python to call the repr() function for each element of your tuple.

In documents:

str () :

Returns a string containing a beautifully printable representation of the object. For strings, this returns the string by itself.

repr () :

Returns a string containing the view for printing the object.

This means that if the object you call repr() on is a string object (in python this is all an object), it shows you how different characters are represented.

@ Your specific question: I assume that "..." indicates that this is a string. If you call repr () in int, there is no "...".

0
source

Source: https://habr.com/ru/post/1369372/


All Articles