Python Training: Strings
Key Concepts Related to Strings
Strings in Python are sequences of characters, enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). They are immutable, meaning once created, their content cannot be changed. Python provides various methods and operations to manipulate strings efficiently.
1. String Creation
Strings can be created using single quotes, double quotes, or triple quotes. Triple quotes are often used for multi-line strings.
# Single quotes single_quote_string = 'Hello, World!' # Double quotes double_quote_string = "Python is fun!" # Triple quotes triple_quote_string = '''This is a multi-line string.'''
2. String Indexing and Slicing
Strings can be indexed and sliced to access specific characters or substrings. Indexing starts at 0, and negative indexing starts from the end of the string.
sample_string = "Python" # Indexing first_char = sample_string[0] # Output: 'P' last_char = sample_string[-1] # Output: 'n' # Slicing substring = sample_string[1:4] # Output: 'yth'
3. String Methods
Python provides numerous built-in methods to manipulate strings. Some commonly used methods include upper()
, lower()
, replace()
, and split()
.
text = "Hello, Python!" # Convert to uppercase upper_text = text.upper() # Output: 'HELLO, PYTHON!' # Convert to lowercase lower_text = text.lower() # Output: 'hello, python!' # Replace a substring replaced_text = text.replace("Python", "World") # Output: 'Hello, World!' # Split the string into a list split_text = text.split(", ") # Output: ['Hello', 'Python!']
4. String Concatenation and Repetition
Strings can be concatenated using the '+' operator and repeated using the '*' operator.
str1 = "Hello" str2 = "World" # Concatenation concatenated_string = str1 + ", " + str2 # Output: 'Hello, World' # Repetition repeated_string = str1 * 3 # Output: 'HelloHelloHello'
5. Escape Sequences
Escape sequences are used to include special characters in strings. Common escape sequences include \n
for a newline and \t
for a tab.
escaped_string = "Hello\nWorld\tPython" # Output: # Hello # World Python
6. String Formatting
String formatting allows you to insert variables into strings. Python supports multiple formatting methods, including the format()
method and f-strings (Python 3.6+).
name = "Alice" age = 25 # Using format() method formatted_string = "My name is {} and I am {} years old.".format(name, age) # Using f-string (Python 3.6+) f_string = f"My name is {name} and I am {age} years old."