Posts

Showing posts with the label String formatting

Python - String formatting

Image
Using the format() method, you can format a string by replacing placeholders with specific values. Special arguments are used, enclosed in curly braces ({}), to put into a string. Named Parameters We can use the format() method to define the parameters in a string format and pass the values for these parameters in the method: text = "Hello, {name}." .format(name= "Carl" ) print(text)     # Hello, Carl.   info = "Name: {name}, Age: {age}" .format(name= "Carl" , age= 16 ) print(info)     # Name: Carl,  Age: 16 Additionally, the arguments in the format method have the same name as the parameters in the line. Thus, in the first scenario, if the parameter is named name, the argument to which the value is assigned is likewise named name. Parameters by position Another option is to sequentially pass a set of arguments to the format method and insert them into the formatted line itself, with the number of the arguments denoted by curly brackets (numberi