Strings are a fundamental data type in Python used to represent text. In this topic, we'll explore everything you need to know about handling strings in Python, from basic operations to more advanced techniques.
Strings in Python can be created by enclosing text within single quotes ('
) or double quotes ("
).
# Example of creating strings
str1 = 'Hello'
str2 = "Python"
Concatenation is the process of combining strings together.
# Example of string concatenation
full_str = str1 + ' ' + str2
print(full_str) # Output: Hello Python
You can find the length of a string using the len()
function.
# Example of finding string length
length = len(full_str)
print(length) # Output: 11
Individual characters in a string can be accessed using indexing. Indexing starts from 0 for the first character.
# Example of string indexing
first_char = full_str[0]
print(first_char) # Output: H
You can extract a substring from a string using slicing.
# Example of string slicing
substring = full_str[6:]
print(substring) # Output: Python
These methods modify the case (uppercase, lowercase, etc.) of a string.
text = "hello world"
print(text.capitalize()) # Output: "Hello world"
text = "HELLO WORLD"
print(text.lower()) # Output: "hello world"
text = "hello world"
print(text.upper()) # Output: "HELLO WORLD"
text = "hello world"
print(text.title()) # Output: "Hello World"
These methods help find substrings or replace parts of a string.
text = "hello world"
print(text.find("world")) # Output: 6
print(text.find("python")) # Output: -1
text = "hello world"
print(text.replace("world", "Python")) # Output: "hello Python"
text = "hello hello world"
print(text.count("hello")) # Output: 2
These methods remove leading, trailing, or both leading and trailing whitespace (or specified characters) from a string.
text = " hello world "
print(text.strip()) # Output: "hello world"
text = " hello world "
print(text.lstrip()) # Output: "hello world "
text = " hello world "
print(text.rstrip()) # Output: " hello world"
These methods deal with encoding strings or formatting them for display.
text = "hello world"
print(text.encode()) # Output: b'hello world'
print(text.encode("utf-16")) # Output: b'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
text = "Hello, {}!"
print(text.format("Alice")) # Output: "Hello, Alice!"
Case Manipulation: capitalize(), lower(), upper(), title() – Modify the case of the string. Searching and Replacing: find(), replace(), count() – Search for substrings or replace them. Whitespace Handling: strip(), lstrip(), rstrip() – Remove unwanted whitespace or characters. Encoding and Formatting: encode(), format() – Encode strings into bytes or format them with placeholders. Happy Coding!❤️