在 Python 中连接字符串和浮点数

连接字符串和浮点数:

  1. 使用 str() 类将浮点数转换为字符串。
  2. 使用加法 + 运算符连接两个字符串。
  3. 结果将是浮点数和字符串的连接。
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

在 Python 中连接字符串和浮点数

第一个示例使用加法 + 运算符连接字符串和浮点数。

在将浮点数连接到字符串之前,我们必须使用 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 = 'zadmei'

result = f'{var1} {var2} com'
print(result)  # ?️ www zadmei com

在 Python 中连接字符串和浮点数

确保将表达式包裹在花括号 – {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 字符代表定点符号。

该字符将数字格式化为小数点后指定位数的十进制数。

当使用格式化的字符串文字时,我们不必显式地将浮点数转换为字符串。 转换是自动为我们完成的。