In Python, a string is a sequence of characters enclosed in quotes. You can use single quotes (‘), double quotes (“), triple single quotes (”’), or triple double quotes (“””) to create strings. Here are some fundamental aspects of working with strings in Python:single_quote_str = ‘Hello, World!’
double_quote_str = “Hello, World!”
triple_single_quote_str = ”’Hello,
World!”’
triple_double_quote_str = “””Hello,
World!”””
Common String Operations
—-Concatenation—-
You can concatenate strings using the + operator:
str1 = “Hello”
str2 = “World”
concatenated_str = str1 + “, ” + str2 + “!”
# Output: ‘Hello, World!’
––Repetition—
You can repeat strings using the * operator:
repeated_str = “Hello” * 3
# Output: ‘HelloHelloHello’
—Accessing Characters–
You can access individual characters in a string using indexing (0-based):
char = concatenated_str[1]
# Output: ‘e’
—Slicing—
You can slice strings to get a substring:
substring = concatenated_str[0:5]
# Output: ‘Hello’
—String Methods—
Python provides a rich set of methods for string manipulation. Here are a few:
- lower(): Converts all characters to lowercase.
lower_str = concatenated_str.lower()
# Output: ‘hello, world!’
- upper(): Converts all characters to uppercase.
upper_str = concatenated_str.upper()
# Output: ‘HELLO, WORLD!’
- strip(): Removes leading and trailing whitespace.
stripped_str = ” Hello, World! “.strip()
# Output: ‘Hello, World!’
- split(): Splits the string into a list of substrings.
split_str = concatenated_str.split(“, “)
# Output: [‘Hello’, ‘World!’]
- join(): Joins a list of strings into a single string.
joined_str = “, “.join(split_str)
# Output: ‘Hello, World!’
–String Formatting–
- Using f-stringsΒ Β (Python 3.6+)
name = “Alice”
age = 30
formatted_str = f”My name is {name} and I am {age} years old.”
# Output: ‘My name is Alice and I am 30 years old.’
- Using format() method
formatted_str = “My name is {} and I am {} years old.”.format(name, age)
# Output: ‘My name is Alice and I am 30 years old.’
- Using % operator
formatted_str = “My name is %s and I am %d years old.” % (name, age) # Output: ‘My name is Alice and I am 30 years old.’
—Multiline Strings—
Triple quotes (”’ or “””) can be used to create multiline strings:
multiline_str = “””This is a
multiline string that spans
multiple lines.”””
Checking Substrings
You can check if a substring exists within a string using the in keyword:
contains_hello = “Hello” in concatenated_str
# Output: True
These are some of the basic and commonly used operations and methods for handling strings in Python. Strings are versatile and widely used in various applications, so getting comfortable with these operations is essential for efficient coding in Python.