如何返回当前状态的字符串表示?

时间:2017-03-26 17:02:29

标签: python

我必须创建一个函数,该函数返回当前状态的字符串表示形式,如下所示:

Alt = 4.00 Vel = 0.00 Fuel = 0 Str = 4

我必须准确匹配格式(2位小数,间距等)

def current_status():
    global altitude
    global velocity
    global fuel
    global strength
    global gravity
    altitude="{0:.2f}".format(altitude)
    velocity="{0:.2f}".format(velocity)
    string=("Alt =",altitude, "Vel =",velocity,"Fuel =",fuel,"Str =",strength)
    return str(string)

1 个答案:

答案 0 :(得分:1)

您可以使用str.format()方法,该方法使用带有特殊replacement fields的字符串来指定数据的格式。

你不必声明所有这些变量global - 虽然它没有伤害 - 因为这将在函数中自动假设,因为它们中没有一个被定义,只有他们的当前值被引用。

# Define some global variables for testing.
altitude = 4.
velocity = 0.
fuel = 0
strength = 0
gravity = 42

def current_status():
    return "Alt = {:02.2f}, Vel = {:02.2f}, Fuel = {:,d}, Str = {:,d}".format(
                                                        altitude, velocity, fuel, strength)

# Try it out.
print(current_status())

输出:

Alt = 4.00, Vel = 0.00, Fuel = 0, Str = 0