#atom
ID: PY-001
Date: [Insert Date]
Content:
In Python, a string is a sequence of characters enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are immutable, meaning once created, they cannot be changed. Python provides a rich set of methods for string manipulation.
Ways to Create Strings in Python:
-
Using Single Quotes:
str1 = 'Hello, World!' -
Using Double Quotes:
str2 = "Hello, World!" -
Using Triple Quotes (for Multi-line Strings):
str3 = ''' This is a multi-line string. ''' -
Using the
str()Constructor:str4 = str(123) # Converts the number 123 to a string -
Using f-Strings (Formatted String Literals):
name = 'Alice' greeting = f'Hello, {name}!' # "Hello, Alice!"
Common String Methods in Python:
-
len(): Get the length of a string.text = 'Hello' print(len(text)) # 5 -
upper()andlower(): Convert case.text = 'Hello' print(text.upper()) # "HELLO" print(text.lower()) # "hello" -
strip(): Remove leading and trailing whitespace.text = ' Hello, World! ' print(text.strip()) # "Hello, World!" -
replace(): Replace parts of a string.text = 'Hello, World!' print(text.replace('World', 'Alice')) # "Hello, Alice!" -
split(): Split a string into a list based on a delimiter.text = 'apple,banana,cherry' print(text.split(',')) # ['apple', 'banana', 'cherry'] -
join(): Join a list of strings into a single string.fruits = ['apple', 'banana', 'cherry'] print(', '.join(fruits)) # "apple, banana, cherry" -
find()andindex(): Search for substrings.text = 'Hello, World!' print(text.find('World')) # 7 print(text.index('World')) # 7 -
startswith()andendswith(): Check if a string starts or ends with a specific substring.text = 'Hello, World!' print(text.startswith('Hello')) # True print(text.endswith('!')) # True
Connections:
Connections:
Sources:
- From: Python