About Lesson
String Operations and Methods
- Definition: A string is a sequence of characters enclosed in quotes. Strings are immutable, meaning they cannot be changed after creation.
- Common String Operations:
- Concatenation: Combining two or more strings using the
+
operator. pythonstr1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Output: Hello World
- Repetition: Repeating a string multiple times using the
*
operator. pythonstr1 = "Hello" result = str1 * 3 print(result) # Output: HelloHelloHello
- Indexing: Accessing individual characters in a string using their index. python
str1 = "Hello" print(str1[0]) # Output: H
- Slicing: Extracting a substring from a string using a range of indices. python
str1 = "Hello" print(str1[1:4]) # Output: ell
- Concatenation: Combining two or more strings using the
Common String Methods:
len()
: Returns the length of the string. pythonstr1 = "Hello" print(len(str1)) # Output: 5
lower()
andupper()
: Converts the string to lowercase or uppercase. pythonstr1 = "Hello" print(str1.lower()) # Output: hello print(str1.upper()) # Output: HELLO
strip()
: Removes leading and trailing whitespace. pythonstr1 = " Hello " print(str1.strip()) # Output: Hello
replace()
: Replaces a substring with another substring. pythonstr1 = "Hello World" print(str1.replace("World", "Python")) # Output: Hello Python
split()
: Splits the string into a list of substrings based on a delimiter. pythonstr1 = "Hello,World" print(str1.split(",")) # Output: ['Hello', 'World']
Formatting Strings
- Definition: Formatting strings allows you to insert variables and expressions into strings.
- Methods:
f-strings
(formatted string literals): Introduced in Python 3.6, they provide a concise way to embed expressions inside string literals. pythonname = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.") # Output: My name is Alice and I am 25 years old.
format()
method: Another way to format strings. pythonname = "Alice" age = 25 print("My name is {} and I am {} years old.".format(name, age)) # Output: My name is Alice and I am 25 years old.