在 Python 中连接字符串和浮点数
连接字符串和浮点数:
-
使用
str()
类将浮点数转换为字符串。 -
使用加法
+
运算符连接两个字符串。 - 结果将是浮点数和字符串的连接。
my_str = 'The float is: '
my_float = 3.456789
# ✅ 使用 (+) 运算符
result = my_str + str(my_float)
print(result) # 👉️ The float is: 3.456789
# -----------------------------------
# ✅ 使用 f-string
result = f'{my_str}{my_float}'
print(result) # 👉️ The float is: 3.456789
print(f'{my_str}{my_float:.2f}') # 👉️ The float is: 3.46
# -----------------------------------
# ✅ 使用 str.format()
result = '{}{}'.format(my_str, my_float)
print(result) # 👉️ The float is: 3.456789
第一个示例使用加法 +
运算符连接字符串和浮点数。
在将浮点数连接到字符串之前,我们必须使用 str()
函数将其转换为字符串。
my_str = 'The float is: '
my_float = 3.456789
result = my_str + str(my_float)
print(result) # 👉️ The float is: 3.456789
这是必要的,因为加法
+
运算符左侧和右侧的值需要是兼容的类型。
这意味着我们要么必须将字符串转换为浮点数,要么将浮点数转换为字符串。
如果在将浮点数连接到字符串时需要将浮点数四舍五入为 N 位小数,请使用 round()
函数。
my_str = 'The float is: '
my_float = 3.456789
result = my_str + str(round(my_float, 2))
print(result) # 👉️ The float is: 3.46
round
函数采用以下 2 个参数:
- number 小数点后四舍五入到 ndigits 精度的数字
- ndigits 小数点后的位数,运算后应有的数(可选)
round
函数返回小数点后四舍五入到 ndigits 精度的数字。
或者,我们可以使用格式化的字符串文字。
使用 f 字符串连接字符串和浮点数
使用格式化的字符串文字来连接字符串和浮点数,例如 result = f'{my_str}{my_float}'
。 格式化的字符串文字使我们能够通过在字符串前加上 f 来在字符串中包含变量和表达式。
my_str = 'The float is: '
my_float = 3.456789
result = f'{my_str}{my_float}'
print(result) # 👉️ The float is: 3.456789
result = f'{my_str}{my_float:.2f}'
print(result) # 👉️ The float is: 3.46
格式化字符串文字 f-strings
让我们通过在字符串前面加上 f 来在字符串中包含表达式。
var1 = 'www'
var2 = 'jiyik'
result = f'{var1} {var2} com'
print(result) # 👉️ www jiyik com
确保将表达式包裹在花括号 - {expression}
中。
格式化的字符串文字还使我们能够在表达式块中使用格式规范迷你语言。
如果我们需要将浮点数四舍五入为 N 位小数,则可以使用格式规范迷你语言。
my_str = 'The float is: '
my_float = 3.456789
result = f'{my_str}{my_float:.2f}'
print(result) # 👉️ The float is: 3.46
花括号之间的 f 字符代表定点符号。
该字符将数字格式化为小数点后指定位数的十进制数。
当使用格式化的字符串文字时,我们不必显式地将浮点数转换为字符串。 转换是自动为我们完成的。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。