【问题标题】:Format String - number [closed]格式字符串 - 数字 [关闭]
【发布时间】:2020-07-10 19:18:51
【问题描述】:

这是一个简单的问题,但我需要解释。 在这段代码中为什么输出为 100:

x = 100.1205
y = str(x)[6]
print("{:.{}f}".format(x,y))

【问题讨论】:

  • 输出为{:.{}f}.format(x,y)
  • 输出不是100;它是文字字符串"{:.{}f}.format(x,y)"
  • 这显然是一个错字,应该是print("{:.{}f}".format(x,y)),它确实打印了100
  • 谢谢,它是如何格式化字符串的,我的意思是步骤

标签: python string format


【解决方案1】:
x = 100.1205
y = str(x)[6]  ## This is turning x into a string and grabbing the 6th character which is 0
print("{:.{}f}".format(x,y)) # this is saying print x to the decimal place 
#specified by the value of y (zeroth digit) which is 100

【讨论】:

  • 这意味着删除小数点?
  • 你可以这样想。如果你输入 print("{:.{}f}".format(x,2)) 它会打印出 100.12
  • x.yf 表示在.y 小数点后打印x 数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多