📜 Strings in Python
📖 String Basics
Strings are a fundamental data type in Python used to handle text. They can be created using single, double, or triple quotes, which can span multiple lines.
🔎 String Operations
Escape Characters in Strings
Escape sequences are used to include special characters in strings:
[BASH]# Include a new line character
print(“First Line\nSecond Line”)
# Include a tab character
print(“Column1\tColumn2”)
# Include a backslash character
print(“This is a backslash: \\”)[/BASH]
String Concatenation and Indexing
Strings can be concatenated and indexed to extract specific parts:
[BASH]# Concatenation
first_name = “John”
last_name = “Doe”
full_name = first_name + ” ” + last_name
print(full_name) # Output: John Doe
# Indexing and Slicing
phrase = “Python Programming”
print(phrase[7:18]) # Output: Programming
print(phrase[:6]) # Output: Python
print(phrase[-11:]) # Output: Programming
[/BASH]
String Immutability
Since strings are immutable, any modification creates a new string:
[BASH]original = “immutable”
modified = original.replace(“immutable”, “mutable”)
print(modified) # Output: mutable
[/BASH]
🧩 String Methods
Common String Methods
[BASH]# Using .find() to locate a substring
text = “Hello, Python!”
position = text.find(“Python”)
print(position) # Output: 7
# Using .replace() to replace a substring
new_text = text.replace(“Python”, “World”)
print(new_text) # Output: Hello, World!
# Using .strip() to remove leading and trailing whitespace
whitespace_str = ” Hello, World! “
print(whitespace_str.strip()) # Output: Hello, World!
[/BASH]
String Formatting
String formatting allows for embedding variables into strings:
[BASH]# Using .format() for string formatting
name = “Alice”
age = 30
formatted_str = “Name: {}, Age: {}”.format(name, age)
print(formatted_str) # Output: Name: Alice, Age: 30
# Using f-strings for string formatting (Python 3.6+)
formatted_str_f = f”Name: {name}, Age: {age}”
print(formatted_str_f) # Output: Name: Alice, Age: 30
[/BASH]
✍️ Exercises: String Manipulation
1- Print a string with a newline character:
[BASH]
print(“Line 1\nLine 2\nLine 3”)
[/BASH]
2- Print a string with a tab character:
[BASH]
print(“Name\tAge”)
print(“Alice\t30”)
[/BASH]
3- Replace characters in a string:
[BASH]
sentence = “I love Python.”
new_sentence = sentence.replace(“Python”, “programming”)
print(new_sentence) # Output: I love programming.
[/BASH]
4- Find and replace a substring in a string:
[BASH]
quote = “To be or not to be, that is the question.”
updated_quote = quote.replace(“be”, “exist”)
print(updated_quote) # Output: To exist or not to exist, that is the question.
[/BASH]
🔢 Numbers in Python
📖 Numeric Types
Python supports different numeric types, including integers and floats. You can also use scientific notation for large numbers.
[BASH]
# Integer
integer_value = 1_000_000
print(integer_value) # Output: 1000000
# Float with exponential notation
float_value = 1.75e5
print(float_value) # Output: 175000.0
[/BASH]
Integer and Float Types
Basic Arithmetic Operations
Perform various arithmetic operations using Python:
[BASH]
# Arithmetic operations
a = 15
b = 4
print(a + b) # Output: 19
print(a – b) # Output: 11
print(a * b) # Output: 60
print(a / b) # Output: 3.75
# Zero Division Error Handling
try:
result = a / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)
# Rounding Numbers
number = 2.675
print(round(number, 2)) # Output: 2.68
# Floor Division and Modulus
print(a // b) # Output: 3
print(a % b) # Output: 3
[/BASH]
🧩 Advanced Numeric Operations
Exponentiation
[BASH]
# Exponentiation
base = 2
exponent = 3
result = base ** exponent
print(result) # Output: 8
[/BASH]
Use Functions
[BASH]
#Using round(), abs(), pow(), and .is_integer()
number = -5.432
print(round(number, 2)) # Output: -5.43
print(abs(number)) # Output: 5.432
print(pow(2, 3)) # Output: 8
print(3.0.is_integer()) # Output: True
print(3.1.is_integer()) # Output: False
[/BASH]
✍️ Exercises: Numeric Operations
1- Calculate the area of a circle:
[BASH]
import math
radius = float(input(“Enter the radius of the circle: “))
area = math.pi * (radius ** 2)
print(f”The area of the circle is: {area:.2f}”)
[/BASH]
2- Convert a float to an integer and vice versa:
[BASH]
float_num = 123.456
int_num = int(float_num)
print(f”Float: {float_num}, Integer: {int_num}”)
int_num = 789
float_num = float(int_num)
print(f”Integer: {int_num}, Float: {float_num}”)
[/BASH]
3- Calculate the product of two numbers provided by the user:
[BASH]
num1 = float(input(“Enter the first number: “))
num2 = float(input(“Enter the second number: “))
product = num1 * num2
print(f”The product of {num1} and {num2} is {product}.”)
[/BASH]
4- Format a number as currency and percentage:
[BASH]
amount = 1000
percentage = 0.85
# Currency formatting
print(f”${amount:,.2f}”)
# Percentage formatting
print(f”{percentage:.0%}”)
[/BASH]
✍️ Exercises: Numeric Operations
1- Calculate the area of a circle:
🧠 Test Your Knowledge with Kahoot!
Thank you for learning about Python with us! To make this learning experience even more interactive, we invite you to test your Python knowledge by playing our Kahoot quiz. Click the link below to get started and challenge yourself!
🎮 Play the Python Intro Quiz on Kahoot!
Have fun and see how much you’ve learned! 🚀