In Python, strings str are immutable sequences of Unicode characters used to represent text.
Strings in Python can be declared in several ways, by enclosing them in single quotes ' or double quotes ".
simple_string = 'Hello, world!'
double_string = "Hello, world!"
triple_string = """This is an example
of a string with multiple lines."""
Strings in Python are immutable (meaning they cannot be modified once created). Any operation that appears to modify a string actually creates a new string.
Internally they are represented as sequences of Unicode characters. So we can use special characters or characters specific to certain languages without any problems.
Special Characters
Strings in Python support special characters to represent line breaks (\n), tabs (\t), quotes within strings (\", \'), among others.
string_with_newline = "First line\nSecond line"
print(string_with_newline)
# Output:
# First line
# Second line
String Operations
Python supports several basic operations and manipulations with text strings:
String Concatenation
String concatenation is performed using the + operator:
string1 = "Hello"
string2 = " world"
concatenated_string = string1 + string2
print(concatenated_string) # Output: "Hello world"
Indexing and Slicing
It is possible to access individual characters of a string using indices and to slice it to obtain substrings:
message = "Hello world"
first_character = message[0]
substring = message[1:5] # From index 1 to 5 (not inclusive)
print(first_character) # Output: "H"
print(substring) # Output: "ello"
Formatting Methods
Python offers several methods for formatting strings, such as format() and formatted string literals (f-string):
name = "Luis"
age = 30
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message) # Output: "Hello, my name is Luis and I am 30 years old."
# F-string (python 3.6+)
fstring_message = f"Hello, my name is {name} and I am {age} years old."
print(fstring_message) # Output: "Hello, my name is Luis and I am 30 years old."
Useful Methods
In addition to the basic string manipulation methods, Python offers specialized methods for verifying and transforming strings:
Verification Methods
startswith(prefix): ReturnsTrueif the string starts with the given prefix.endswith(suffix): ReturnsTrueif the string ends with the given suffix.isalpha(): ReturnsTrueif all characters in the string are letters.isdigit(): ReturnsTrueif all characters in the string are digits.
string = "Python is awesome"
print(string.startswith("Py")) # Output: True
print(string.endswith("me")) # Output: True
print(string.isalpha()) # Output: False (because there are spaces and not just letters)
Manipulation Methods
Python provides numerous methods for manipulating strings, such as upper(), lower(), strip(), replace(), split(), among others:
text = " Hello, world! "
uppercase_text = text.upper()
text_without_spaces = text.strip()
print(uppercase_text) # Output: " HELLO, WORLD! "
print(text_without_spaces) # Output: "Hello, world!"
Transformation Methods
split(separator): Splits the string into a list of substrings separated by the specified separator.join(iterable): Joins the elements of an iterable (like a list) into a single string using the string as a separator.
text = "Hello, how are you?"
words = text.split(", ")
print(words) # Output: ['Hello', 'how are you?']
list_of_words = ['Hello', 'how', 'are', 'you?']
joined_text = ' '.join(list_of_words)
print(joined_text) # Output: "Hello how are you?"
