大家好!最近在学习 Python 编程的过程中,我接触到了字符串格式化这个功能。通过实践,我了解了使用 format 方法和 f-string 来处理字符串,收获颇丰,在这里分享一下我的学习心得。
代码呈现:
#1.
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
for name in contacts:
message_content = """
律回春渐,新元肇启。
新岁甫至,福气东来。
金""" + year + """贺岁,欢乐祥瑞。
金""" + year + """敲门,五福临门。
给""" + name + """及家人拜年啦!
新春快乐,""" + year + """年大吉!"""
print(name)
print(message_content)
#2.format方法
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
for name in contacts:
message_content = """
律回春渐,新元肇启。
新岁甫至,福气东来。
金{0}贺岁,欢乐祥瑞。
金{0}敲门,五福临门。
给{1}及家人拜年啦!
新春快乐,{0}年大吉!""".format(year,name)
print(name)
print(message_content)
#3.
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
for name in contacts:
message_content = """
律回春渐,新元肇启。
新岁甫至,福气东来。
金{0}贺岁,欢乐祥瑞。
金{0}敲门,五福临门。
给{1}及家人拜年啦!
新春快乐,{0}年大吉!""".format(year,name) #0表示第一个参数,1表示第二个参数
print(name)
print(message_content)
#4.
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
for name in contacts:
message_content = """
律回春渐,新元肇启。
新岁甫至,福气东来。
金{current_year}贺岁,欢乐祥瑞。
金{current_year}敲门,五福临门。
给{receiver_name}及家人拜年啦!
新春快乐,{current_year}年大吉!""".format(current_year = year,receiver_name =name)
print(name)
print(message_content)
#5.
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
for name in contacts:
message_content = """
律回春渐,新元肇启。
新岁甫至,福气东来。
金{year}贺岁,欢乐祥瑞。
金{year}敲门,五福临门。
给{name}及家人拜年啦!
新春快乐,{year}年大吉!""".format(year = year,name =name) #等号后面为参数值
print(name)
print(message_content)
#6.f-字符串。
contacts = ["老刘","老婆","老贾","老周","老张","老人"]
year = "虎"
name = "老人"
for name in contacts:
message_content = f"""
律回春渐,新元肇启。
新岁甫至,福气东来。
金{year}贺岁,欢乐祥瑞。
金{year}敲门,五福临门。
给{name}及家人拜年啦!
新春快乐,{year}年大吉!"""
print(name)
print(message_content)
#7.
gpa_dict = {"老刘":3.66,"老贾":3.42,"老周":3.86,"老李":3.19,"老人":3.99}
for name, gpa in gpa_dict.items():
print("{0}您好,您当前的绩点为{1}".format(name,gpa))#{1:.2f}保留两位小数点
#print(f"{name}您好,您当前的绩点为:{gpa:.2f}")
知识介绍:
- format 方法为字符串提供了强大的格式化能力。它允许我们在字符串中使用占位符,然后通过传递参数来替换这些占位符,使字符串更具动态性。
- f-string(格式化字符串字面值)允许我们在字符串中直接嵌入表达式,只需在字符串前加上 f 或 F 就可以使用。
总结:
通过这次学习,我深刻体会到了 Python 字符串格式化的强大与便捷。无论是传统的 format 方法还是现代化的 f-string,都为处理动态字符串提供了高效的解决方案。在今后的编程中,我会根据实际需求灵活选择使用它们,让代码更加简洁、可读且富有表现力。希望我的分享能对同样在学习字符串格式化的朋友们有所帮助!