C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python String format() MethodPython format() method is used to perform format operations on string. While formatting string a delimiter {} (braces) is used to replace it with the value. This delimeter either can contain index or positional argument. Signatureformat(*args, **kwargs) Parameters
Return TypeIt returns a formatted string. Let's see some examples to understand the format() method. Python String format() Method Example 1An example of simple format method which format string using positional delimiter. # Python format() function example # Variable declaration str = "Java" str2 = "C#" # Calling function str3 = "{} and {} both are programming languages".format(str,str2) # Displaying result print(str3) Output: Java and C# both are programming languages Python String format() Method Example 2The delimiter (braces) are using numerical index to replace and format string. # Python format() function example # Variable declaration str = "Java" str2 = "C#" # Calling function str3 = "{1} and {0} both are programming languages".format(str,str2) # Displaying result print(str3) Output: C# and Java both are programming languages Python String format() Method Example 3Formatting numerical value in different-different number systems. See the below example. # Python format() function example # Variable declaration val = 10 # Calling function print("decimal: {0:d}".format(val)); # display decimal result print("hex: {0:x}".format(val)); # display hexadecimal result print("octal: {0:o}".format(val)); # display octal result print("binary: {0:b}".format(val)); # display binary result Output: decimal: 10 hex: a octal: 12 binary: 1010 Python String format() Method Example 4Formating float and percentile in string is pretty easy. # Python format() function example # Variable declaration val = 100000000 # Calling function print("decimal: {:,}".format(val)); # formatting float value print("decimal: {:.2%}".format(56/9)); # formatting percentile value Output: decimal: 100,000,000 decimal: 622.22%
Next TopicPython Strings
|