Introduction
In Python, a string is a sequence of characters enclosed within either single quotes (') or double quotes ("). It's an immutable data type, meaning its contents cannot be changed after creation.
Creating Strings
Python
# Single quotes
string1 = 'Hello, world!'
# Double quotes
string2 = "This is a string"
Multiline Strings
For multiline strings, use triple quotes (either single or double):
Python
multiline_string = """This is a multiline
string using triple quotes"""
Accessing Characters
You can access individual characters using indexing (starts from 0):
Python
string = "Python"
first_char = string[0] # Output: 'P'
Slicing Strings
Extract a substring using slicing:
Python
string = "Python"
substring = string[2:5] # Output: 'tho'
String Length
Find the length of a string using len():
Python
string = "Hello"
length = len(string) # Output: 5
String Immutability
Strings are immutable, meaning you cannot change individual characters.
Python
string = "Hello"
string[0] = 'J' # This will raise a TypeError
String Concatenation
Combine strings using the + operator:
Python
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name
print(message) # Output: Hello, Alice
String Methods
Python provides many built-in methods for string manipulation:
- upper(): Converts to uppercase
- lower(): Converts to lowercase
- strip(): Removes whitespace from the beginning and end
- split(): Splits a string into a list of substrings
- join(): Joins elements of an iterable into a string
- replace(): Replaces occurrences of a substring with another
- find(): Returns the index of the first occurrence of a substring
Case Conversion:
- upper(): Converts all characters to uppercase.
Python
text = "hello"
print(text.upper()) # Output: HELLO
- lower(): Converts all characters to lowercase.
Python
text = "WORLD"
print(text.lower()) # Output: world
- capitalize(): Capitalizes the first character of the string.
Python
text = "hello, world"
print(text.capitalize()) # Output: Hello, world
- title(): Capitalizes the first character of each word.
Python
text = "hello world"
print(text.title()) # Output: Hello World
- swapcase(): Swaps cases, lower to upper and vice versa.
Python
text = "HeLlO"
print(text.swapcase()) # Output: hEllO
Searching and Replacing:
- find(sub[, start[, end]]): Returns the index of the first occurrence of the substring.
- rfind(sub[, start[, end]]): Returns the index of the last occurrence of the substring.
- index(sub[, start[, end]]): Similar to find(), but raises a ValueError if not found.
- rindex(sub[, start[, end]]): Similar to rfind(), but raises a ValueError if not found.
- count(sub[, start[, end]]): Returns the number of non-overlapping occurrences of the substring.
- replace(old, new[, count]): Replaces occurrences of the old substring with the new one.
Whitespace Manipulation:
- strip(): Removes leading and trailing whitespace.
- lstrip(): Removes leading whitespace.
- rstrip(): Removes trailing whitespace.
Splitting and Joining:
- split(sep=None, maxsplit=-1): Splits a string into a list of substrings based on the separator.
- partition(sep): Splits a string into three parts based on the first occurrence of the separator.
- rpartition(sep): Splits a string into three parts based on the last occurrence of the separator.
- join(iterable): Joins elements of an iterable into a string using the string as a separator.
Checking String Content:
- startswith(prefix[, start[, end]]): Checks if the string starts with the specified prefix.
- endswith(suffix[, start[, end]]): Checks if the string ends with the specified suffix.
- isalpha(): Returns True if all characters are alphabetic.
- isdigit(): Returns True if all characters are digits.
- isalnum(): Returns True if all characters are alphanumeric.
- isspace(): Returns True if all characters are whitespace.
Other Useful Methods:
- len(string): Returns the length of the string.
- max(string): Returns the highest character in the string.
- min(string): Returns the lowest character in the string.
Example:
Python
text = " This is a sample string "
words = text.strip().split()
capitalized_words = [word.capitalize() for word in words]
new_text = " ".join(capitalized_words)
print(new_text) # Output: This Is A Sample String
Example
Python
text = " This is a sample string "
text = text.strip() # Remove whitespace
words = text.split() # Split into a list of words
new_text = " ".join(words) # Join words with spaces
print(new_text)
Working with String in various types