Python:如何调用字符串中的值? [重复]

问题描述 投票:0回答:3

我是Python新手。在下面的代码(或参见附件)中,我想调用程序最后一步中字符串内输入的所有数字。我该怎么办?

print "how old are you?",
age = raw_input()
print "how tall are you?",
height = raw_input()

print = (expected outcome: You're X old, X tall, etc.)
python python-2.7
3个回答
1
投票

我更喜欢的一种简单方法是使用字符串格式化运算符,如下所示:

>>> age = 10
>>> height = 72
>>> print "you're %s years old and %s cm tall" % (age, height)
you're 10 years old and 72 cm tall
>>>

0
投票

酷!,欢迎使用 python 编码!,有很多方法可以做你想做的事情,我将向你展示一种,但请随意寻找另一种

print "how old are you?",
age = raw_input()
print "how tall are you?",
height = raw_input()

print("You're " + age + " old, " + height + " tall, etc.")

额外:您可以向

raw_input
添加参数,使其类似于:

age = raw_input("how old are you?")
height = raw_input("how tall are you?")

print("You're " + age + " old, " + height + " tall, etc.")

0
投票

您可以打印任意数量的内容,例如:

print "You're", age, "years old and", height, "centimeters tall"

或者你可以使用字符串格式

print "You're {} years old and {} centimeters tall".format(age,height)

示例

>>> age=29
>>> height=160
>>> print "You're", age, "years old and", height, "centimeters tall"
You're 29 years old and 160 centimeters tall
>>> print "You're {} years old and {} centimeters tall".format(age,height)
You're 29 years old and 160 centimeters tall
>>> 

有几种方法可以做到这一点,如其他答案和评论中所示,我最喜欢的是字符串格式

此外,如果您需要将这些输入转换为数字以对其进行数学运算,请相应地使用

int
float

x = int(raw_input("write a number: "))

此外,当你学习 python 时,我建议从最新版本 python 3.5 开始,如果需要,你可以稍后调整到旧版本

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