Nested Lists & String Formatting

 

A list as an item of another list.

Accessing Nested List

Code

list_a = [5, "Six", [8, 6], 8.2]
print(list_a[2])
PYTHON

Output

[8, 6]

Accessing Items of Nested List

Example - 1

Code

list_a = [5, "Six", [8, 6], 8.2]
print(list_a[2][0])
PYTHON

Output

8

Example - 2

Code

list_a = ["Five", "Six"]
print(list_a[0][1])
PYTHON

Output

i

String Formatting

Code

name = input()
age = int(input())
msg = ("Hi " + name + ". You are "+ str(age) + " years old.")
print(msg)
PYTHON

String formatting simplifies this concatenation.

It increases the readability of code and type conversion is not required.

Add Placeholders

Add placeholders

{}
where the string needs to be formatted.

msg = "Hi {}. You are {} years old."
msg.format(val_1, val_2,..)
PYTHON

Inserts values inside the string’s placeholder

{}

Code

name = "Raju"
age = 10
msg = "Hi {}. You are {} years old."
print(msg.format(name, age))
PYTHON

Output

Hi Raju. You are 10 years old.

Number of Placeholders

Code

name = "Raju"
age = 10
msg = "Hi {}. You are {} years old {}."
print(msg.format(name, age))
PYTHON

Output

IndexError: Replacement index 2 out of range for positional args tuple

Numbering Placeholders

Numbering placeholders, will fill values according to the position of arguments.

Code

name = input()
age = int(input())
msg = "Hi {0}. You are {1} years old."
print(msg.format(name, age))
PYTHON

Input

Raju
10

Output

Hi Raju. You are 10 years old.

Code

name = input()
age = int(input())
msg = "Hi {1}. You are {0} years old."
print(msg.format(name, age))
PYTHON

Input

Raju
10

Output

Hi 10. You are Raju years old.

Naming Placeholder

Naming placeholders will fill values according to the keyword arguments.

Code

name = input()
age = int(input())
msg = "Hi {name}. You are {age} years old."
print(msg.format(name=name, age=age))
PYTHON

Input

Raju
10

Output

Hi Raju. You are 10 years old.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form