Use string formatting in Python programming

python_bg

Here are 3 ways to format strings and print the output of the asked (input) variables. The last method is in my opinion the best way to go. But I’m no programmer and this is my first day of Python language training (all these posts are for personal reference)

Option 1:

				
					#Asking name and age variable
asked_name = input("What is your name: ")
asked_age = input("What is your age: ")

# Insert new line (\n) and print message of the asked name and age.
message1 = "\nHello {fname}, your age is {fage}" .format(fname=asked_name, fage=asked_age)
print(message1)
				
			

The output of the script above:

				
					└───$ python3 input_command1.py
What is your name: Sander
What is your age: 100

Hello sander, your age is 100
				
			

 

Option 2:

				
					#Asking name and age variable
asked_name = input("What is your name: ")
asked_age = input("What is your age: ")

# Insert new line (\n) and print message of the asked name and age.
message2 = "\nHello {0}, your age is {1}".format(asked_name, asked_age)
print(message2)
				
			

The output of the script above:

				
					└───$ python3 input_command2.py
What is your name: Sander
What is your age: 99

Hello sander, your age is 99
				
			

 

Option 3:

				
					#Asking name and age variable
asked_name = input("What is your name: ")
asked_age = input("What is your age: ")

# Insert new line (\n) and print message of the asked name and age.
message3 = "Hello {}, your age is {}".format(asked_name, asked_age)
print(message3)
				
			

The output of the script above:

				
					└───$ python3 input_command3.py
What is your name: Sander
What is your age: 88

Hello Sander, your age is 88
				
			

 

The best option 3 (my opinion):

				
					#Asking name and age variable
asked_name = input("What is your name: ")
asked_age = input("What is your age: ")

# Insert new line (\n) and print message of the asked name and age.
print(f"\nYour name is {asked_name} and your age is {asked_age} ")
				
			

The output of the script above:

				
					└───$ python3 input_command3.py
What is your name: Sander
What is your age: 77

Your name is Sander and your age is 77
				
			
Leave a Reply

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

Previous Post
bgmetagoofil

Extract metadata of public files from targeted websites

Next Post
python_bg

Use Boolean True or False in Python programming

Related Posts
md5-integrity-check

Integrity with MD5 or SHA-1

[title size=”2″ content_align=”center” style_type=”default” sep_color=”” margin_top=”” margin_bottom=”” class=”” id=””]Check integrity with MD5 or SHA-1[/title][separator style_type=”none” top_margin=”5″ bottom_margin=”” sep_color=””…
Read More