Advanced understanding of using the str.format() function

str.format()is a method for formatting strings that provides a flexible and readable way to insert variables into a string. Here are str.format()some examples of using :

1. Basic usage:

name = "Alice"
age = 30
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)

Output:

Hello, my name is Alice and I am 30 years old.

2. Use positional parameters:

message = "Hello, my name is {0} and I am {1} years old.".format(name, age)
print(message)

Output:

Hello, my name is Alice and I am 30 years old.

3. Use keyword arguments:

message = "Hello, my name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(message)

Output:

Hello, my name is Bob and I am 25 years old.

4. Format numbers:

pi = 3.1415926
message = "The value of pi is approximately {:.2f}".format(pi)
print(message)

Output:

The value of pi is approximately 3.14

5. Alignment and padding:

formatted_num = "{:<10}".format(42)
print(formatted_num)

Output:

42        

6. Format date:

from datetime import datetime
today = datetime.today()
formatted_date = "{:%Y-%m-%d}".format(today)
print(formatted_date)

Output:

2023-09-18

str.format()Methods allow you to use curly braces as placeholders in a string {}and insert corresponding values ​​via positional or keyword arguments. It also supports various format specifications, such as alignment, precision, date format, etc., providing very flexible and powerful string formatting functions.

Learn to test code

# 在string中的format方法中使用位置参数来进行参数传递,同时使用::对数据进行格式化输出
def string3(username=None, number=None):
    string = 'Hello, {0}, 成绩提升了 {1:.1f} %'.format(username, number)
    print(string)


# 在format方法中使用关键字参数来进行参数传递
def string4():
    name = 'wangguowei'
    string = 'hello world from {name}'.format(name=name)
    print(string)


# 使用传统的花括号对字符串进行占位,等待参数传入,将字符串进行格式化输出
def string5():
    name = 'wangguowei'
    string = "hello world from {}".format(name)
    print(string)


if __name__ == '__main__':
    string3(username='wangguowe',number=10)
    string4()
    string5()

operation result

D:\ANACONDA\envs\pytorch\python.exe C:/Users/Administrator/Desktop/Code/Learn_Pyhon3.7/liaoxuefeng/function/dir1/common_function.py
Hello, wangguowe, 成绩提升了 10.0 %
hello world from wangguowei
hello world from wangguowei

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_44943389/article/details/132978626