formatted string in python code example

Example 1: formatted string python

# Newer f-string format
name = "Foo"
age = 12
print(f"Hello, My name is {name} and I'm {age} years old.")
# output :
# Hello, my name is Foo and I'm 12 years old.

Example 2: python string format

string_a = "Hello"
string_b = "Cena"

# Index based:
print("{0}, John {1}"
      .format(string_a, string_b))
# Object based:
print("{greeting}, John {last_name}"
      .format(greeting=string_a, last_name=string_b))

Example 3: str.format python 3

print("Sammy the {pr} {1} a {0}.".format("shark", "made", pr = "pull request"))

Example 4: python f string

import random
name = input("What is your name? ") #Gets needed input
value = int(input(f"Give random value, {name}: ")) # The {name} means it puts the variable name there
multiplier = random.randint(3, 6)
print("Now multiplying your value...")
complete_value = multiplier * value
print(f"Your value is... {complete_value}") # Same here with complete_value

Example 5: python format strings

name = "Rick"
age = 42
print(f"My name is {name} and I am {age} years old")

Example 6: formatted string in python

>>> name = "world"
>>> print(f"Hello {name}!)"
'Hello world!'

Tags:

Misc Example