YouTip LogoYouTip

Att String Format

# Python2.x Python format() Function [![Image 3: Python Strings](#) Python Strings](#) * * * Starting from Python 2.6, a new string formatting function `str.format()` was introduced, which enhances the functionality of string formatting. The basic syntax uses `{}` and `:` to replace the previous `%`. The `format` function can accept an unlimited number of arguments, and the positions do not need to be in order. ## Example >>>"{} {}".format("hello", "world")# No position specified, default order'hello world'>>>"{0} {1}".format("hello", "world")# Position specified'hello world'>>>"{1} {0} {1}".format("hello", "world")# Position specified'world hello world' You can also set parameters: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-print("Website name: {name}, URL {url}".format(name="", url="www."))# Set parameters via dictionary site = {"name": "", "url": "www."} print("Website name: {name}, URL {url}".format(**site))# Set parameters via list index my_list = ['', 'www.']print("Website name: {0}, URL {0}".format(my_list))# "0" is required The output is: Website name: , URL www. Website name: , URL www. Website name: , URL www. You can also pass objects to `str.format()`: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-class AssignValue(object): def __init__ (self, value): self.value = value my_value = AssignValue(6)print('value is: {0.value}'.format(my_value))# "0" is optional The output is: value is: 6 ### Number Formatting The following table shows various ways to format numbers using `str.format()`: >>> print("{:.2f}".format(3.1415926))3.14 | Number | Format | Output | Description | | --- | --- | --- | --- | | 3.1415926 | {:.2f} | 3.14 | Keep two decimal places | | 3.1415926 | {:+.2f} | +3.14 | Keep two decimal places with sign | | -1 | {:-.2f} | -1.00 | Keep two decimal places with sign | | 2.71828 | {:.0f} | 3 | No decimal places | | 5 | {:0>2d} | 05 | Pad with zeros (left-aligned, width 2) | | 5 | {:x<4d} | 5xxx | Pad with x (right-aligned, width 4) | | 10 | {:x10d} | 13 | Right-aligned (default, width 10) | | 13 | {:<10d} | 13 | Left-aligned (width 10) | | 13 | {:^10d} | 13 | Center-aligned (width 10) | | 11 | '{:b}'.format(11)'{:d}'.format(11)'{:o}'.format(11)'{:x}'.format(11)'{:#x}'.format(11)'{:#X}'.format(11) | 10111113 b 0xb0XB | Number base conversion | `^`, `` represent center, left, and right alignment respectively, followed by the width. After the `:`, you can specify the fill character, which must be a single character. If not specified, the default is to fill with spaces. `+` indicates to show `+` before positive numbers and `-` before negative numbers; a space indicates to add a space before positive numbers. `b`, `d`, `o`, `x` represent binary, decimal, octal, and hexadecimal respectively. Additionally, we can use curly braces `{}` to escape curly braces, as shown in the following example: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-print("{} corresponds to position {{0}}".format("")) The output is: corresponds to position {0} * * Python Strings](#)
← Java Print ParallelogramJsref Reduce β†’