Python String Formatting
String Formatting
The format() method is used to perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument.
Syntax:
str.format(*args, **kwargs)
Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
Contents:
Basic formatting:
Example-1:
>>> '{} {}'.format('Python', 'Format')
'Python Format'
>>>
>>> '{} {}'.format(10, 30)
'10 30'
>>>
This following statement allows re-arrange the order of display without changing the arguments.
Example-2:
>>> '{1} {0}'.format('Python', 'Format')
'Format Python'
>>>
Value conversion:
The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.
In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.
Setup:
class Data(object): def __str__(self): return 'str' def __repr__(self): return 'repr'
Example-1:
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
x='{0!s} {0!r}'.format(Data())
print (x)
Output:
str repr
In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...) instead.
Example-2:
class Data(object):
def __repr__(self):
return 'räpr'
x='{0!r} {0!a}'.format(Data())
print(x)
Output:
räpr r\xe4pr
Padding and aligning strings:
A value can be padded to a specific length. See the following examples where the value '15' is encoded as part of the format string.
Note: The padding character can be spaces or a specified character.
Example:
Align right:
>>> '{:>15}'.format('Python')
' Python'
>>>
Align left:
>>> '{:15}'.format('Python')
'Python '
>>>
By argument:
In the previous example, the value '15' is encoded as part of the format string. It is also possible to supply such values as an argument.
Example:
>>> '{:<{}s}'.format('Python', 15)
'Python '
>>>
In the following example we have used '*' as a padding character.
Example:
>>> '{:*<15}'.format('Python')
'Python*********'
>>>
Align center:
Example:
>>> '{:^16}'.format('Python')
' Python '
>>>
Truncating long strings:
In the following example, we have truncated ten characters from the left side of a specified string.
Example:
>>> '{:.10}'.format('Python Tutorial')
'Python Tut'
>>>
By argument:
Example:
>>> '{:.{}}'.format('Python Tutorial', 10)
'Python Tut'
>>>
Combining truncating and padding
In the following example, we have combined truncating and padding.
Example:
>>> '{:10.10}'.format('Python')
'Python '
>>>
Numbers:
Integers:
>>> '{:d}'.format(24)
'24'
>>>
Floats:
>>> '{:f}'.format(5.12345678123)
'5.123457'
>>>
Padding numbers:
Similar to strings numbers.
Example-1:
>>> '{:5d}'.format(24)
' 24'
>>>
The padding value represents the length of the complete output for floating points. In the following example '{:05.2f}' will display the float using five characters with two digits after the decimal point.
Example-2:
>>> '{:05.2f}'.format(5.12345678123)
'05.12'
>>>
Signed numbers:
By default only negative numbers are prefixed with a sign, but you can display numbers prefixed with the positive sign also.
Example-1:
>>> '{:+d}'.format(24)
'+24'
>>>
You can use a space character to indicate that negative numbers (should be prefixed with a minus symbol) and a leading space should be used for positive numbers.
Example-2:
>>> '{: d}'.format((- 24))
'-24'
>>>
Example-3:
>>> '{: d}'.format(24)
' 24'
>>>
You can control the position of the sign symbol relative to the padding.
Example-4:
>>> '{:=6d}'.format((- 24))
'- 24'
>>>
Named placeholders:
Both formatting styles support named placeholders. Here is an example:
Example-1:
>>> data = {'first': 'Place', 'last': 'Holder!'}
>>> '{first} {last}'.format(**data)
'Place Holder!'
>>>
.format() method can accept keyword arguments.
Example-2:
>>> '{first} {last}'.format(first='Place', last='Holder!')
'Place Holder!'
>>>
Datetime:
You can format and print datetime object as per your requirement.
Example:
>>> from datetime import datetime
>>> '{:%Y-%m-%d %H:%M}'.format(datetime(2016, 7, 26, 3, 57))
'2016-07-26 03:57'
>>>
Previous: Python String
Next: Python Lists
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Find current directory and file's directory:
To get the full path to the directory a Python file is contained in, write this in that file:
import os dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)
To get the current working directory use
import os cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The os and os.path modules.
- The __file__ constant
- os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
- os.path.dirname(path) (returns "the directory name of pathname path")
- os.getcwd() (returns "a string representing the current working directory")
- os.chdir(path) ("change the current working directory to path")
Ref: https://bit.ly/3fy0R6m
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework