String in Python
String in Python
we can concatenate multiple strings as well as use other data types by converting them
to strings using the str() function:
age = 25
message = 'I am ' + str(age) + ' years old.'
print(message)
You can also use negative indices to access characters from the end of the string:
last_char = str1[-1] # Last character
print(last_char)
#output: n
4. String Slicing:
substring = str1[0:5]
# Output: 'Hello'
#output: Hello
substring = str1[6:] # From index 6 to the end
print(substring)
6. String Methods
Strings in Python come with a variety of built-in methods that allow you to manipulate
and analyze them.
a) upper(): Converts all characters in the string to uppercase.
str1 = 'Hello, World!'
u = str1.upper()
print(u)
Output:
HELLO, WORLD!
b) lower(): Converts all characters in the string to lowercase.
lower = str1.lower()
print(lower)
Output:
hello, world!
c) replace(): Replaces a substring with another substring.
python
str1 = 'Hello, World!'
replacestr= str1.replace('World', 'Python')
print(replacestr)
Output:
Hello, Python!
d) strip(): Removes leading and trailing whitespaces.
str1 = ' Hello, World! '
stripstring = str1.strip()
print(stripstring)
Output:
Hello, World!
e) split(): Splits the string into a list of substrings based on a delimiter (default is
space).
str1 = 'Python is great'
split_string = str1.split()
print(split_string)
Output:
['Python', 'is', 'great']
You can specify a custom delimiter:
str1 = 'apple,banana,cherry'
split_string = str1.split(',')
print(split_string)
Output:
['apple', 'banana', 'cherry']
f) join(): Joins elements of a list into a single string using a delimiter.
fruits = ['apple', 'banana', 'cherry']
joined_string = ', '.join(fruits)
print(joined_string)
Output:
apple, banana, cherry
7. Escape Sequences
Escape sequences are used to insert special characters into strings. Some common
ones:
• \': Single quote
• \": Double quote
• \\: Backslash
• \n: Newline
• \t: Tab
Example:
str1 = 'Hello\nWorld!'
print(str1)
Output:
Hello
World!
Python flow control refers to how the execution of code is controlled based on conditions
and loops. There are three main types of flow control structures in Python:
1. Conditional Statements
Conditional statements are used to execute code only when a certain condition is true.
Python supports the if, elif, and else statements for decision-making.
if statement
The if statement allows you to run a block of code when the condition is true.
Eg.-
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
if-else statement
If the condition in the if block is false, the else block will execute.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
if-elif-else statement
The elif (else if) statement allows for multiple conditions to be checked. If the first condition
fails, the next condition is evaluated, and so on.
x=5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
Output:
x is equal to 5
Nested if statements
You can also nest if statements within each other for more complex conditions.
x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
Output:
2. Loops
Loops are used to repeat a block of code multiple times. Python supports two main types of
loops: for and while.
for loop
A for loop is used to iterate over a sequence (like a list, tuple, string, or range).
Output:
apple
banana
cherry
Output:
0
1
2
3
4
while loop
i=1
while i <= 5:
print(i)
i += 1 # Increment i to avoid an infinite loop
Output:
1
2
3
4
5
Nested loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
3. Control Statements
Control statements like break, continue, and pass are used to change the behavior of loops.
break statement
The break statement is used to exit a loop prematurely when a condition is met.
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
Output:
0
1
2
3
4
continue statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
for i in range(5):
if i == 3:
continue # Skip the iteration when i equals 3
print(i)
Output:
0
1
2
4
pass statement
The pass statement is a placeholder and does nothing. It’s used when a statement is
syntactically required but you don’t want to execute any code.
for i in range(5):
if i == 3:
pass # Do nothing, continue the loop
print(i)
Output:
0
1
2
3
4
• if, else, elif: Used to make decisions and execute code based on conditions.
• for loop: Iterates over a sequence of elements.
• while loop: Repeats a block of code while a condition is true.
• break: Exits the loop prematurely.
• continue: Skips the current iteration and moves to the next.
• pass: Does nothing, used as a placeholder.
These control structures allow Python programs to handle complex decision-making, loops,
and flow management, making your code more efficient and dynamic.
Basic Data Structure:
Python provides several basic data structures that are fundamental to working with data.
These include:
1. Lists
2. Tuples
3. Dictionaries
4. Sets
Each of these data structures serves different purposes and has unique properties.
1. Lists
A list is an ordered, mutable (changeable) collection of items, which can be of different data
types (e.g., integers, strings, objects). Lists are created by placing elements inside square
brackets ([]), separated by commas.
Example:
print(my_list)
Output:
print(my_list[0]) # Output: 1
• Modifying elements:
my_list[1] = 10
print(my_list) # Output: [1, 10, 3, 'apple', 'banana', True]
• Appending elements:
my_list.append("new item")
• Removing elements:
my_list.remove("apple")
2. Tuples
A tuple is similar to a list, but it is immutable (i.e., once created, you cannot modify it).
Tuples are defined by placing elements inside parentheses (()), separated by commas.
Example:
print(my_tuple)
Output:
• Ordered: Elements are stored in a specific order and can be accessed by index.
• Immutable: Once defined, elements cannot be added, removed, or changed.
print(my_tuple[0]) # Output: 1
Advantages of Tuples:
• Since tuples are immutable, they can be used as keys in dictionaries or elements in
sets, unlike lists.
• They are more memory-efficient than lists.
3. Dictionaries
Example:
print(my_dict)
Output:
• Unordered: Items have no defined order (in Python 3.7+, they maintain insertion
order).
• Mutable: You can change, add, or remove key-value pairs.
my_dict["age"] = 30 # Update
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}
• Removing elements:
del my_dict["city"]
print(my_dict)
print(key, value)
# Output:
# name Alice
# age 30
# country USA
4. Sets
A set is an unordered collection of unique items. Sets are defined by placing elements inside
curly braces ({}), and duplicate elements are automatically removed.
Example:
my_set = {1, 2, 3, 4, 4, 5}
print(my_set)
Output:
Copy code
{1, 2, 3, 4, 5}
• Unordered: Elements do not have a specific order and cannot be accessed by index.
• Unique: Duplicate elements are not allowed.
• Mutable: You can add or remove elements (though the set itself must contain
immutable elements).
• Adding elements:
my_set.add(6)
• Removing elements:
my_set.remove(4)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
Summary