본문 바로가기
Python

[Python] 3 Ways of Formatted String

by llHoYall 2021. 1. 22.

There are 3 ways to write a formatted string in Python3.

Let's check it one by one.

Formatted String with Placeholder

This method seems like a C language.

It uses string-formatting operator %.

print("String: %c, %s" % ('h', 'python'))
# String: hello, python

print("Integer: %d, %i" % (3, 7))
# Integer: 3, 7

print("Floating: %f, %F, %3.2f" % (2.818, 1.414, 3.14159))
# Floating: 2.818000, 1.414000, 3.14

print("Hex: %x" % 28)
# Hex: 1c

print("octal: %o" % 10)
# octal: 12

I think there is no difficult thing to understand.

Let's take a look at more complicated usage.

print("Leading Symbol: %#d, %#o, %#x" % (25, 25, 25))
# Leading Symbol: 25, 0o31, 0x19

print("Align: %5d, %-5d" % (3, 7))
# Align:     3, 7

print("Padding Zero: %05d, %-05d" % (3, 7))
# Padding Zero: 00003, 7

print("Percent: %d %%" % 73)
# Percent: 73 %

There are more symbols but it is rarely used.

Formatted String with .format() Function

Let's see the example first.

print('{}, {}, {}'.format('Hello', 7, 3.14))
# Hello, 7, 3.14

print('{1}-{2}-{0}'.format('zero', 'one', 'two'))
# one-two-zero

print('{name}, {age}, {name}'.format(age=18, name='HoYa'))
# HoYa, 18, HoYa

This method is also easy to understand.

And, it also has extra functions.

print('{:s}, {:b}, {:o}, {:d}, {:x}, {:f}'.format('Hello', 5, 10, 7, 23, 3.14))
# Hello, 101, 12, 7, 17, 3.140000

print('{:5d}, {:-5d}, {:05d}'.format(3, 5, 7))
#     3,     5, 00007

print('{:#b}, {:#o}, {:#d}, {:#x}'.format(5, 11, 7, 27))
# 0b101, 0o13, 7, 0x1b

print('{:3.4f}'.format(3.141592))
# 3.1416

You can easily understand it because it looks like the previous one.

Formatted String with String Literals (f-String)

I like this method, and I usually use this method.

name = 'HoYa'
age = 18
height = 177.5

print(f'{name}, {age}, {height}, and {3}')
# HoYa, 18, 177.5, and 3

It looks more modern way, isn't it?

import math

print(f'{math.pi:3.5}')
# 3.1416

number = 7

print(f'{(lambda x: x * 2)(number)}')
# 14

print(f'{number:5}, {number:<5}, {123:>02}, {123:>05}')
#     7, 7    , 123, 00123

print(f'0b{6:04b}, 0o{11:04o}, {number:04d}, 0x{35:04x}')
# 0b0110, 0o0013, 0007, 0x0023

This method can even use a lambda function.

 

I hope this post will help you.

댓글