Strings
Strings in Python are sequences of characters and come with a variety of built-in methods for manipulation and analysis. Here are some common operations:
# Creating a string
my_string = "Hello, World!"
# Accessing characters
first_char = my_string[0] # 'H'
last_char = my_string[-1] # '!'
# Slicing
substring = my_string[0:5] # 'Hello'
# String length
length = len(my_string) # 13
# Changing case
upper_case = my_string.upper() # 'HELLO, WORLD!'
lower_case = my_string.lower() # 'hello, world!'
# Replacing substrings
replaced_string = my_string.replace("World", "Python") # 'Hello, Python!'
# Splitting strings
words = my_string.split(", ") # ['Hello', 'World!']
# Joining strings
joined_string = " ".join(words) # 'Hello World!'
# Checking for substrings
contains_hello = "Hello" in my_string # True
# Stripping whitespace
stripped_string = " Hello ".strip() # 'Hello'
# Testing string properties
is_alpha = "Hello".isalpha() # True
is_digit = "12345".isdigit() # True