如何将分数的选择部分传递给字符串进行显示?

问题描述 投票:-2回答:3

我想显示分数的前4位数,并将其传递给字符串以显示在我的情节的标题中。我检查了这个post,但我找不到一个优雅的方式。

我尝试使用代码作为问题的最简单方法我不希望在此之后显示%

train_MSE=mean_squared_error(Y_train, Y_RNN_Train_pred)
print("Train MSE:",train_MSE_)
#Train MSE: 0.33068236552127656

train_MSE_ = "%.4f%%" % train_MSE
print("Train MSE:",train_MSE_)
#Train MSE: 0.3307% 
#expected result without '%' ---> 0.337

plt.plot(Y_RNN_Test_pred[0],'b-')
plt.title(f'Test MSE={test_MSE_}', fontsize=15, fontweight='bold')
plt.show()
python numpy floating-point digits fractions
3个回答
2
投票

你需要在最后删除%%

train_MSE_ = "%.4f" % train_MSE_

0
投票

你可以使用format命令

print('{0:.4f}'.format(0.264875464))

结果

0.2649

所以你可以编写你的代码,如:

train_MSE_=0.264875464
print('Train MSE:{0:.4f}'.format(train_MSE_))

reslut

Train MSE:0.2649

0
投票

你可以这样做:

print("Train MSE : {:.4f}".format(train_MSE_))

您可以在此处查看有关格式字符串的更多详细信息:https://docs.python.org/3.7/library/string.html#formatstrings

© www.soinside.com 2019 - 2024. All rights reserved.