Python String Formatting

by Atakan

Hi, we will examine the issue of string formatting in Python.
We can provide user side output with many different methods. There are many different methods. let’s start

Example student object :

student = {'name': 'John', "surname": 'Smith', 'age': 10}
content = 'Hi my name is ' + student['name'] + ' ' + student['surname'] + ' and ' + str(student['age']) + ' years old.'
print(content)

Result :

Hi my name is John Smith and 10 years old.
content = 'Hi my name is {} {} and {} years old.'.format(student['name'], student['surname'], str(student['age']))
print(content)

Result :

Hi my name is John Smith and 10 years old.
content = 'Hi my name is {0} {1} and {2} years old.'.format(student['name'], student['surname'], str(student['age']))
print(content)

Result :

Hi my name is John Smith and 10 years old.
content = 'Hi my name is {0[name]} {0[surname]} and {0[age]} years old.'.format(student)
print(content)

Result :

Hi my name is John Smith and 10 years old.
content = 'Hi my name is {name} {surname} and {age} years old.'.format(**student)
print(content)

Result :

Hi my name is John Smith and 10 years old.
print('Number: {:d}'.format(1000))

Result :

Number: 1000
print('Number: {:d}'.format(-1000))

Result :

Number: -1000
print('Float: {:f}'.format(5.2000))

Result :

Float: 5.200000
print('Float: {:.2f}'.format(5.2000))

Result :

Float: 5.20
print('String: {:s}'.format('Hi there'))

Result :

String: Hi there
Class custom format
class Student(object):
    def __init__(self):
        self.name = "John"
        self.surname = "Smith"
        self.age = 10

    def __format__(self, format_spec):
        if (format_spec == "student-format"):
            return "Hi my name is " + self.name + " " + self.surname + "  and " + str(self.age) + " years old."
        return self.name + " " + self.surname + str(self.age)
print('{:student-format}'.format(Student()))

Result :

Hi my name is John Smith and 10 years old.
print('{}'.format(Student()))

Result :

John Smith10

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More