Python: How to call the values in a string?

Python: How to call the values in a string?

one simple way that i prefer is to use the string formatting operator like this:

>>> age = 10
>>> height = 72
>>> print youre %s years old and %s cm tall % (age, height)
youre 10 years old and 72 cm tall
>>>

Cool!, welcome to coding in python!, there are lots of ways to do what you want, ill show you one, but feel free to look for another

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

print(Youre  + age +  old,  + height +  tall, etc.)

EXTRA: you can add params to raw_input and make it like:

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

print(Youre  + age +  old,  + height +  tall, etc.)

Python: How to call the values in a string?

you can print as many thing as you want for example:

print Youre, age, years old and, height, centimeters tall

or you can use string format

print Youre {} years old and {} centimeters tall.format(age,height)

example

>>> age=29
>>> height=160
>>> print Youre, age, years old and, height, centimeters tall
Youre 29 years old and 160 centimeters tall
>>> print Youre {} years old and {} centimeters tall.format(age,height)
Youre 29 years old and 160 centimeters tall
>>> 

there are several ways on how to do it as illustrated in the others answers and comments, my favorite is the string format

Also if you need to convert those input in numbers to do math on them use int or float accordingly

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

furthermore, as you are learning python I recommend starting with the newest version, python 3.5 you can later ajust to older version if needed

Leave a Reply

Your email address will not be published. Required fields are marked *