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))
Name ='Tame Tamir'
Age =14
Formatted_string ='Hello, my name is {name}, I am {age} years old.'.format(name=Name,age=Age)# after the formatting, the variable name inside the {} will be replaced by whatever you declare in the .format() part.print(Formatted_string)# output = Hello, my name is Tame Tamir, I am 14 years old.
print('The {2} {1} {0}'.format('fox','brown','quick'))
result =100/777print('{newvar}'.format(newvar = result))print('the result was {r:0.3f}'.format(r = result))
# Python string format() method# default(implicit) order
default_order ="{}, {} and {}".format('John','Bill','Sean')print('
--- Default Order ---')print(default_order)# order using positional argument
positional_order ="{1}, {0} and {2}".format('John','Bill','Sean')print('
--- Positional Order ---')print(positional_order)# order using keyword argument
keyword_order ="{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')print('
--- Keyword Order ---')print(keyword_order)
# ------------------- string format, f-string ----------------------------# {} is placeholder
num1 =5
num2 =3print(f'{num1} times {num2} is {num1 / num2:.2f}')#2f means print to 2 decimal precision#5 times 3 is 1.67#explicit call format() method
number1 ='One'
number2 ='Two'
number3 ='Three'# default(implicit) order
default_order ="{}, {} and {}".format(number1,number2,number3)print(default_order)# One, Two and Three# order using positional argument
positional_order ="{1}, {0} and {2}".format(number1,number2,number3)print(positional_order)# Two, One and Three# order using keyword argument
keyword_order ="{i}, {j} and {k}".format(j=number1,k=number2,i=number3)print(keyword_order)# Three, One and Two
# use {}, where u want to place integer, or any other datatype.# Use .formate at the end of string, # and finally place data variable in parentheses
a =123.1133
b ="Username"
c =Trueprint("a = {}".format(a))print("b = {}".format(b))print("c = {}".format(c))
# default argumentsprint("Hello {}, your balance is {}.".format("Adam",230.2346))# positional argumentsprint("Hello {0}, your balance is {1}.".format("Adam",230.2346))# keyword argumentsprint("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))# mixed argumentsprint("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))