Skip to content

Sequence Datatypes

these datatypes are used to create variables that can store collection of data items referring with same identifier.

ย 

Sequence Datatype of Python:
1. String
2. List
3. Tuple
4. Set
5. Dictionary

ย 

String:
It is a group of characters or words or phrase. String variable can be created by assigning a phrase inside double or single quotes into an identifier.

๐Ÿ
filename.py
#Example
name="Best"
print(type(name))
name2='Computer'
print(type(name2))

Python treats String as a collection of characters each one is identified individually.

ย 

Each letter in String has a positive index value starts from ‘0’ assigning from left to right.
using index positions we can access individual values of string.

๐Ÿ
filename.py
#Example
name="Best"
print(name)
print(name[2])

Slicing:
Accessing a group of letters from the string using their index positions is called as Slicing.

ย 

Syntax:
StrVar[StartIndex:StopIndex]

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name[2:8])

Starting Index value must be smaller than Stop Index Value.

If you omit Start Index value, slicing starts from beginning letter
If you omit Stop Index value, Slicing continues till ending letter

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name[2:8])
print(name[:8])
print(name[2:])
print(name[:])

There is Negative Indexing also for the String that starts from ‘-1’ assigning from right to left.

using Negative indexing also we can access individual letters or slice it.

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name[-8:-2])
print(name[:-2])
print(name[-8:])

String is immutable we cannot change any letter using its index value.

๐Ÿ
filename.py
#Example:
x='nandini'
x[3]="D"  #raises Error

There are pre-defined functions in Python that can be used with ‘String’ type variable.

ย 

There are two syntaxes for these functions:
funcName(StrVar)
StrVar.funcName()

ย 

Some of the pre-defined functions of String Datatype of Python:
1.The len() function:
used to return the total number of characters in the string.

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(len(name))

2. The strip() method:
used to return the String by eliminating leading and trailing white spaces.

๐Ÿ
filename.py
#Example
name="   Best Computer Institute   "
print(name)
print(name.strip())
print(name)

3. The lower() method:
used to return the String by converting each letter in lower case

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name.lower())
print(name)

4. The upper() method:
used to return the String by converting each letter as upper case

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name.upper())
print(name)

5. The replace() method:
used to return the String by replacing a letter with specified letter.

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name.replace('t','*'))
print(name)

6. The split() method:
used to make words from the string by using a specified separator letter.

๐Ÿ
filename.py
#Example
name="Best Computer Institute"
print(name.split(" "))
print(name)

7. String Concatenation:
Two strings can be combined to create a new string using ‘+’ operator.

๐Ÿ
filename.py
#Example
fname="Best"
lname="Computers"
name=fname+" "+lname
print(name)

String cannot be concatenated with numeric value.

๐Ÿ
filename.py
#Example
x=2
y="3"
var=x+y
print(var)
#results an error

Formatted Print:

๐Ÿ
filename.py
#Example
print("My Name is {}, Marks {}".format("Kundana",99))
print("My Name is {}, Marks {}".format("Varshini",99))
๐Ÿ
filename.py
#Example
print("My Name is %s, Marks %d"%("Kundana",99))
print("My Name is %s, Marks %d"%("Varshini",99))
๐Ÿ
filename.py
#Example
name="Varshini"
marks=97
print(f"My Name is {name}, Marks {marks}")
name="Kundana"
marks=97
print(f"My Name is {name}, Marks {marks}")

The line:
f”{year} is a leap year.”
is an f-string (formatted string literal) in Python. F-strings were introduced in Python 3.6 and provide a concise and readable way to embed expressions inside string literals. Here’s an explanation:

ย 

Components:
1. The f Prefix: The f at the beginning of the string indicates that it is a formatted string. It allows you to include expressions inside curly braces {} that will be evaluated at runtime.
2. The {year} Placeholder: The variable year is evaluated and its value is inserted into the string at this position. You can include any valid Python expression inside the {}.
3. The Complete String: “is a leap year.” is just regular text that is part of the string.

ย 

How It Works in Context:
If the value of year is 2024, the f-string:
f”{year} is a leap year.”
will evaluate to:
“2024 is a leap year.”

ย 

Why Use F-Strings?
1. Readability: The syntax is clear and avoids concatenation or using str.format().
2. Efficiency: F-strings are faster than older string formatting methods like % or .format().
3. Flexibility: They can embed complex expressions, not just variables.

ย 

For example:

f”The square of {year} is {year ** 2}.”
If year is 2024, this would evaluate to:
“The square of 2024 is 4098176.”

ย 

Alternative (Older) Methods:
Hereโ€™s how the same functionality could be written using older techniques:
Using String Concatenation:
str(year) + ” is a leap year.”

ย 

Using str.format():
“{} is a leap year.”.format(year)
Both alternatives work, but f-strings are preferred for their clarity and simplicity.

format() Method:
The .format() method is used to insert values into placeholders {} within a string. It is versatile and easier to read compared to the % method.

Syntax:
In Python, you can format output in several ways depending on your requirements. Here are some common methods:

Using format() Method
name = “Anil”
marks = 97
print(“My name is {} and Marks obtained {} .”.format(name, marks))

It is used to pass different values to the place holders of String for displaying

๐Ÿ
filename.py
#Example
str1="My Name is {}, Marks: {}"
print(str1.format("Anil",99))
print(str1.format("Gowtham",100))

Using % Formatting (Old Method):

๐Ÿ
filename.py
name = "Anil"
marks = 97
print("My name is %s and Marks obtained %d." % (name, marks))

Formatting Numbers with format():

๐Ÿ
filename.py
num = 1234.56789
print("Formatted Number: {:.2f}".format(num))  # 2 decimal places

Using f-strings for Number Formatting:

๐Ÿ
filename.py
num = 1234.56789
print(f"Formatted Number: {num:.2f}")  # 2 decimal places
print(f"Formatted Number: {num:.0f}")  # integer(rounded)

Practice Questions:
1. Write a Python program that prints the following output using format():
Name: John
Age: 25
Salary: $5000.75

2. Using f-strings, display the following output:

Product: Laptop
Price: $1299.99
Stock: 50 units

3. Write a Python program to format the number 123.456789 to:
Two decimal places
Integer format (rounded)