Data Structure & Algorithms | String in Python
A string is a data type in programming that represents a sequence of characters. In Python, strings are represented using the str class. Strings are immutable in Python, which means that once a string is created, its contents cannot be modified.
To create a string in Python, you can simply enclose a sequence of characters in single quotes (‘’) or double quotes (“”).
my_string = 'Hello, world!'
Some common operations that can be performed on strings include concatenation (joining two or more strings together), slicing (extracting a portion of a string), and searching for a substring within a string.
Python provides several built-in methods for working with strings, such as the len()
function (which returns the length of a string), the lower()
method (which returns a copy of a string with all characters in lowercase), the upper()
method (which returns a copy of a string with all characters in uppercase), and the split()
method (which splits a string into a list of substrings based on a delimiter).
# Concatenation
first_name = 'John'
last_name = 'Doe'
full_name = first_name + ' ' + last_name
print(full_name) # Output: John Doe
# Slicing
my_string = 'Hello, world!'
substring = my_string[0:5]
print(substring) # Output: Hello
# Searching
my_string = 'Hello, world!'
if 'world' in my_string:
print('Found it!') # Output: Found it!
# Length
my_string = 'Hello, world!'
length = len(my_string)
print(length) # Output: 13
# Lowercase
my_string = 'Hello, world!'
lowercase = my_string.lower()
print(lowercase) # Output: hello, world!
# Uppercase
my_string = 'Hello, world!'
uppercase = my_string.upper()
print(uppercase) # Output: HELLO, WORLD!
# Splitting
my_string = 'Hello, world!'
words = my_string.split(',')
print(words) # Output: ['Hello', ' world!']
There are several algorithms that can be applied to strings in Python, depending on what you’re trying to accomplish.
Reverse a string
You can reverse a string in Python using slicing.
my_string = 'Hello, world!'
reversed_string = my_string[::-1]
print(reversed_string) # Output: !dlrow ,olleH
Occurrences of a substring
You can use the count()
method to count the number of occurrences of a substring within a string.
my_string = 'Hello, world!'
count = my_string.count('l')
print(count) # Output: 3
String is a palindrome
You can check if a string is a palindrome (i.e., reads the same backwards as forwards) by comparing the string to its reverse.
my_string = 'racecar'
reversed_string = my_string[::-1]
if my_string == reversed_string:
print('It's a palindrome!') # Output: It's a palindrome!