In Python, a string is a sequence of characters, and it is one of the fundamental data types in the language. Strings are used to represent text and are immutable, meaning their values cannot be changed after creation. Here are some key features and operations related to strings:
# Using single quotes
single_quoted = 'Hello, World!'
# Using double quotes
double_quoted = "Hello, World!"
# Using triple quotes for multi-line strings
multi_line = """This is a
multi-line string."""
# Accessing characters by index
first_char = single_quoted[0] # 'H'
last_char = single_quoted[-1] # '!'
# Slicing
substring = single_quoted[7:12] # 'World'
# Length of a string
length = len(single_quoted)
# Converting to uppercase and lowercase
uppercase_str = single_quoted.upper()
lowercase_str = single_quoted.lower()
# Concatenation
combined_str = single_quoted + " How are you?"
# String formatting
formatted_str = "My name is {} and I am {} years old.".format("Alice", 30)
# Concatenation
full_greeting = "Hello" + ", " + "World!"
# Repetition
repeated_str = "abc" * 3
# Newline
new_line_str = "This is line 1.\\\\nThis is line 2."
# Tab
tabbed_str = "Item\\\\tQuantity"
name = "Alice"
age = 25
formatted_str = f"My name is {name} and I am {age} years old."
# Splitting a string into a list
words = single_quoted.split()
# Joining elements of a list into a string
sentence = ' '.join(words)
# Stripping leading and trailing whitespace
stripped_str = " Hello, World! ".strip()