0% found this document useful (0 votes)
16 views

String in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

String in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

String in Python

In Python, a string is a sequence of characters enclosed in either single quotes ('...') or


double quotes ("..."). Strings are immutable, meaning once created, they cannot be modified.
You can use strings for various operations like concatenation, slicing, formatting, and more.
Here are some basic examples:
1. Creating a string:
str1 = 'Hello, World!'
str2 = "Python"
2. String concatenation:
result = str1 + ' ' + str2
# Output: 'Hello, World! 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)

#output: I am 25 years old.


3. Accessing string characters (indexing):
first_char = str1[0]
# Output: 'H'

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'

• If start is omitted, Python assumes it to be 0.


• If end is omitted, Python assumes it to be the length of the string.
str1 = 'Hello, World!'
substring = str1[:5] # From the beginning to index 4
print(substring)

#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!

thon Program Flow Control:

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 (e.g., if, else, elif)


2. Loops (e.g., for, while)
3. Control Statements (e.g., break, continue, pass)

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:

x is not greater than 5

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:

x is greater than 5 and y is greater than 15

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).

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

Output:

apple
banana
cherry

You can also iterate over a range of numbers:

for i in range(5): # range(5) generates 0, 1, 2, 3, 4


print(i)

Output:

0
1
2
3
4

while loop

A while loop repeats a block of code as long as a condition is true.

i=1
while i <= 5:
print(i)
i += 1 # Increment i to avoid an infinite loop

Output:

1
2
3
4
5

Nested loops

You can nest loops inside one another.

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

Flow Control Summary

• 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:

my_list = [1, 2, 3, "apple", "banana", True]

print(my_list)

Output:

[1, 2, 3, 'apple', 'banana', True]

Key Properties of Lists:

• Ordered: Items have a defined order and can be accessed by index.


• Mutable: You can modify, add, or remove elements.

Common List Operations:

• Accessing elements: Use indexing (starts from 0).

print(my_list[0]) # Output: 1

print(my_list[-1]) # Output: True (last item)

• Slicing: Extract parts of the list.

print(my_list[1:4]) # Output: [2, 3, 'apple']

• Modifying elements:

my_list[1] = 10
print(my_list) # Output: [1, 10, 3, 'apple', 'banana', True]

• Appending elements:

my_list.append("new item")

print(my_list) # Output: [1, 10, 3, 'apple', 'banana', True, 'new item']

• Removing elements:

my_list.remove("apple")

print(my_list) # Output: [1, 10, 3, 'banana', True, 'new item']

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:

my_tuple = (1, 2, 3, "apple", "banana")

print(my_tuple)

Output:

(1, 2, 3, 'apple', 'banana')

Key Properties of Tuples:

• Ordered: Elements are stored in a specific order and can be accessed by index.
• Immutable: Once defined, elements cannot be added, removed, or changed.

Common Tuple Operations:

• Accessing elements: Use indexing, just like lists.

print(my_tuple[0]) # Output: 1

• Slicing: You can extract parts of a tuple.

print(my_tuple[1:3]) # Output: (2, 3)

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

A dictionary is an unordered collection of key-value pairs. Each key in a dictionary must be


unique and immutable (like a string, number, or tuple). Values can be of any data type.
Dictionaries are defined using curly braces ({}) with keys and values separated by a colon
(:).

Example:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

print(my_dict)

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York'}

Key Properties of Dictionaries:

• Unordered: Items have no defined order (in Python 3.7+, they maintain insertion
order).
• Mutable: You can change, add, or remove key-value pairs.

Common Dictionary Operations:

• Accessing values: Use the key to retrieve its associated value.

print(my_dict["name"]) # Output: Alice

• Adding or updating elements:

my_dict["age"] = 30 # Update

my_dict["country"] = "USA" # Add new key-value pair

print(my_dict)

# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

• Removing elements:

del my_dict["city"]

print(my_dict)

# Output: {'name': 'Alice', 'age': 30, 'country': 'USA'}


• Iterating through a dictionary:

for key, value in my_dict.items():

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}

Key Properties of Sets:

• 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).

Common Set Operations:

• Adding elements:

my_set.add(6)

print(my_set) # Output: {1, 2, 3, 4, 5, 6}

• Removing elements:
my_set.remove(4)

print(my_set) # Output: {1, 2, 3, 5, 6}

• Set operations (union, intersection, difference):

set1 = {1, 2, 3}

set2 = {3, 4, 5}

# Union: Elements present in either set

print(set1 | set2) # Output: {1, 2, 3, 4, 5}

# Intersection: Elements present in both sets

print(set1 & set2) # Output: {3}

# Difference: Elements present in set1 but not in set2

print(set1 - set2) # Output: {1, 2}

When to Use Sets:

• To store unique elements.


• To perform mathematical set operations such as union, intersection, and difference.

Summary

• List: Ordered, mutable, allows duplicates.


• Tuple: Ordered, immutable, allows duplicates.
• Dictionary: Unordered collection of key-value pairs, mutable.
• Set: Unordered collection of unique items, mutable.

You might also like