Python strings are one of the most fundamental data types in Python, offering powerful capabilities for text manipulation and representation. A string is essentially a sequence of characters, enclosed in single, double, or triple quotes. Importantly, strings are immutable—once created, their content cannot be changed.
This blog explores the creation, access, and operations on strings, showcasing how Python makes handling text intuitive and efficient. You’ll learn about essential string methods like concatenation, slicing, formatting, and validation. Advanced topics such as raw strings, alignment, and palindrome checks are also covered to deepen your understanding of Python strings.
Whether you’re formatting output, parsing text, or performing complex manipulations, Python’s string capabilities offer a versatile toolkit for both beginners and seasoned developers. Dive in to discover how to unleash the full potential of Python strings in your projects!
A string in Python is a sequence of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). Strings are immutable, which means once created, they cannot be modified.
# Single quotesstr1 = ‘Hello’ # Double quotes str2 = “World” # Triple quotes for multi-line stringsstr3 = ”’Thisis amulti-line string.”’
You can access individual characters in a string using indexing, and substrings using slicing.
string = “Python” # Accessing charactersprint(string[0]) # Output: Pprint(string[-1]) # Output: n # Slicingprint(string[0:3]) # Output: Pytprint(string[2:]) # Output: thon
Operation | Example | Description |
Concatenation | ‘Hello’ + ‘ World’ | Combines strings. |
Repetition | ‘A’ * 3 | Repeats a string n times. |
Membership Check | ‘Py’ in ‘Python’ | Checks if a substring exists. |
String Length | len(‘Python’) | Returns the number of characters. |
Iteration | for char in ‘Python’: print(char) | Loops through each character. |
Below are some important string methods, categorized by their purpose:
Example:
text = “Python Programming”print(text.lower()) # python programmingprint(text.upper()) # PYTHON PROGRAMMINGprint(text.capitalize()) # Python programmingprint(text.title()) # Python Programmingprint(text.swapcase()) # pYTHON pROGRAMMING
Example:
text = ” Hello World “print(text.strip()) # Output: Hello Worldprint(text.lstrip()) # Output: Hello World print(text.rstrip()) # Output: Hello World
Example:
text = “Python is fun and Python is powerful.”print(text.find(“Python”)) # Output: 0print(text.index(“fun”)) # Output: 10print(text.replace(“Python”, “Java”)) # Java is fun and Java is powerful.print(text.count(“Python”)) # Output: 2
Example:
text = “apple,banana,cherry”fruits = text.split(“,”) # [‘apple’, ‘banana’, ‘cherry’]print(fruits) joined_text = “-“.join(fruits) # apple-banana-cherryprint(joined_text)
Example:
text = “Python123″print(text.isalpha()) # False (contains numbers)print(text.isdigit()) # Falseprint(text.isalnum()) # Trueprint(” “.isspace()) # True
Example:
name = “Raghul”age = 25print(“My name is {} and I am {} years old.”.format(name, age)) # Old formattingprint(f”My name is {name} and I am {age} years old.”) # f-strings
Example:
text = “Python”print(text.center(10, “-“)) # –Python–print(text.ljust(10, “-“)) # Python—-print(text.rjust(10, “-“)) # —-Python
name = “Raghul”score = 95print(“%s scored %d points.” % (name, score)) # Old-style formattingprint(“{} scored {} points.”.format(name, score)) # Modern formattingprint(f”{name} scored {score} points.”) # f-strings
path = r”C:\Users\Raghul\Documents”print(path) # Output: C:\Users\Raghul\Documents
text = “Python”reversed_text = text[::-1]print(reversed_text) # nohtyP
def is_palindrome(s): return s == s[::-1] print(is_palindrome(“madam”)) # Trueprint(is_palindrome(“hello”)) # False
Method | Description | |||
lower() | Converts all characters to lowercase. | |||
upper() | Converts all characters to uppercase. | |||
strip() | Removes leading and trailing whitespace. | |||
find(sub) | Finds the first occurrence of sub. | |||
replace(old, new) | Replaces all occurrences of old with new. | |||
split(delim) | Splits the string into a list by the delimiter. | |||
join(iterable) | Joins iterable elements into a string. | |||
isalpha() |
| |||
isdigit() | Checks if all characters are digits. | |||
center(width, char) |
|
Must Read: STM32 ADC: Analog Sensor Reading
Indian Institute of Embedded Systems – IIES