【Moon晨的Python入门笔记】Learn Python The Hard Way(5 & 6)

本文介绍在Python中如何在字符串中嵌入变量,包括使用格式化字符串和.format()语法,以及如何进行浮点数的四舍五入操作。通过具体实例展示了不同方法的应用。

笔记

【1】如何在字符串中嵌入变量

方式一:使用格式化字符串(format string)

  • 创建字符串:每一次使用 单/双引号 把一些文本括起来,就创建了一个字符串
  • 在字符串中嵌入变量:使用格式化字符串(format string)——  字符串以 f 开头,并使用 { } 符号,把变量放在大括号里面

f 是 “格式化”(format)的意思,例如 f"Hello {some}"。f、引号 和 { } 告诉python这是一个格式化字符串,把 变量some 放到大括号的位置

type_of_people=10
x = f"There are {type_of_people} type of people."
# 将变量type_of_people 放入 {}里
print(x)
# 输出:There are 10 type of people.
print(f"I said:'{x}'")
# 输出:I said:'There are 10 type of people.'

方式二:使用.format()语法格式化

x = False
why_are = "Isn't that joke so funny? {}"
print(why_are.format(x))
# .format()函数:将括号内的变量值x,带入前面的 why_are 变量中 字符串里的大括号内
# 输出:Isn't that joke so funny? False

【2】如何将浮点数四舍五入

  • 使用 round() 函数
print(round(3.1415926))
# 输出结果为:
# 3

【3】+ 连接字符串(此方式性能较差,多种连接字符串方式,详见:https://www.cnblogs.com/ccz320/p/6539637.html

w = "This is the left side of..."
e = "a string with a right side"
print(w + e)
# 输出:
# This is the left side of...a string with a right side

相关练习

my_name = 'Moon晨'
my_age = 24
my_height_inches = 62.992126 # inches
my_height = round(2.54 * my_height_inches) # cm
# 1英寸=2.54厘米
# round函数,四舍五入取整数,最后my_height=160

print(f"I'm {my_name}~")
print(f"I'm {my_age} years old and {my_height}cm tall~")
# 用 f函数 时,可以在单/双引号字符串内,通过 {} 大括号,直接引入变量my_age|my_height
# 且如需空格,需手动键入
print("I'm",my_age,"years old and",my_height,"cm tall~")
# 未用 f函数时,需将 字符串 和 变量分开书写:字符串用 单/双引号括起,变量直接写名称
# 然后“字符串 和 变量”,“变量 和 变量” 中间用 分隔号 隔开(分隔号在输出时,相当于 空格)
print("I'm,my_age,years old and,my_height,cm tall~")
# 双引号内整个为字符串,不用f函数 则内无变量


'''
输出为:
I'm Moon晨~
I'm 24 years old and 160cm tall~
I'm 24 years old and 160 cm tall~
I'm,my_age,years old and,my_height,cm tall~
'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值