Python – Format with conversion (stringifiation with str or repr)
There are several ways to format data in Python. The preferred way to format is with the str function. The str function is used to convert objects into strings and stringify objects. The way it is used is str(object), which converts an object into a string. str is used with various formatting options, including adding newlines and tabs. It has other useful functions, such as slicing, reversing, and transposing strings, but we won’t need those for our purposes.
To format data into a nice, neat little string, use the “str” function. For example, this line will print out the string “Hello, World!”:
print(“Hello, World!”)
This line does exactly what you would expect. It prints the string “Hello, World!” on the screen. However, when you want to print many of these strings together, you use the following line of code:
print(“Hello, World!”, end=”\n”)
In this case, the end=”\n” tells the compiler to add a newline character between every two strings you print. If you want to print strings of different lengths, you can simply insert more end characters between the strings.
The Python str function allows you to format your strings in different ways depending on what type of data they contain. However, it only formats as you specify. There’s a lot you can’t do with this function. But when you need to format some strings, this function is still useful.
Difference between str and repr
Difference between str and repr:The Python standard library offers two functions, called str() and repr(), to convert objects to strings and back again.
str() converts an object to a sequence of characters, using its __repr__() method to figure out what sort of string representation to return. str() does not attempt to guess the type of the object; you must provide an explicit type annotation.
repr() takes a more sophisticated approach. It tries to return a printable representation of the object, using the repr() of each of its elements recursively. repr() attempts to be robust and safe, returning something sensible even for objects of complex types such as lists, sets, and dictionaries. If an exception is raised during the process, repr() returns an appropriate error message.
class Point:
def init (self, a, b):
self.x = a
self.y = b
p = Point(2, 3)
print(p) # < main .Point object at 0x10369d750>
print("{}".format(p)) # < main .Point object at 0x10369d750>
print("{!s}".format(p)) # < main .Point object at 0x10369d750>
print("{!r}".format(p)) # < main .Point object at 0x10369d750>
class Point:
def init (self, a, b):
self.x = a
self.y = b
def format (self, spec):
#print(spec) // empty string
return("{{'x':{}, 'y':{}}}".format(self.x,
self.y))
def str (self):
return("({},{})".format(self.x, self.y))
def repr (self):
return("Point({}, {})".format(self.x, self.y))
p = Point(2, 3)
print(p) # (2,3)
print("{}".format(p)) # {'x':2, 'y':3}
print("{!s}".format(p)) # (2,3)
print("{!r}".format(p)) # Point(2, 3)