Print with python f string format

We use make the python print more wonderful with f string (formatted string)


x=1
y=2
z=x+y
print(f'result {x}+{y}={z}')


this will print

result 1+2=3

We can make it more wonderful directly adding expression


x=1
y=2

print(f'{x} times {y} is {x * y}')



We can also set the decimal places in the print


number = 1.123456789
print(f'Four decimal places result {number:.4f}')
#result Four decimal places result 1.1235
#its shows the last digit 5 rather than 4 because of rounded number value


Related Posts

Check if a key exist or not in a python dictionary
July 3, 2024

We can check it with “in” operator and “get()” method In operator here returns the value True or False For example dictionary={“one”:1, “two”:2} if “two” in dictionary: print(“two exist in the dictionary”) Copy Code The get() method returns the value if that key exists. If not exists it returns None dictionary_data={“one”:1, “two”:2} #Here the key […]

Find out median of a list with python
July 3, 2024

Python has wonderful built-in library “statistics” We can find out the median of a list with this library easily with less code import statistics List = [1,2,3,4,5,6,7,8,9,10] result= statistics.median(List) print(result) Copy Code We can also generate list randomly with random module List = [randint(1, 101) for _ in range(50)] this code create a list of […]

How to format JSON with python
July 3, 2024

We can format minified json with python. Python has built in JSON module. We will add indentation in the minified json to format it. First example format JSON add space import json minified_json_example = ‘{“text”:”Hi There”,”type”:”greeting”,”word”:”2″}’ #convert it to python dictonary python_dictionarty = json.loads(minified_json_example) #We will use 4 space indentation to format and convert it […]