Python String
In Python, a string is a sequence of characters enclosed in either single quotes (‘ ‘) or double quotes (” “). It is one of the built-in data types in Python and is commonly used to store and manipulate textual data.
Here are some examples of strings in Python:
1 2 3 4 |
message = "Hello, world!" name = 'John Doe' sentence = "I'm learning Python." empty_string = "" |
Creating multiline strings
In Python, you can create multiline strings by using triple quotes (”’ ”’) or triple double quotes (“”” “””). This allows you to span the string across multiple lines without the need for explicit line breaks.
Here’s an example of creating a multiline string using triple quotes:
1 2 3 4 5 6 7 |
multiline_string = ''' This is a multiline string. It can contain multiple lines of text. You can use single quotes (' ') or double quotes (" "). ''' print(multiline_string) |
Output
This is a multiline string.
It can contain multiple lines of text.
You can use single quotes (' ') or double quotes (" ").
You can also use triple-double quotes to achieve the same result:
1 2 3 4 5 6 7 |
multiline_string = """ This is a multiline string. It can contain multiple lines of text. You can use single quotes (' ') or double quotes (" "). """ print(multiline_string) |
Output
This is a multiline string.
It can contain multiple lines of text.
You can use single quotes (' ') or double quotes (" ").
Using triple quotes allows you to include line breaks and preserve the formatting of the text within the string. It is commonly used for documentation, writing long strings, or creating formatted text blocks.
Using variables in Python strings with the f-strings
In Python, you can use variables within strings using f-strings (formatted string literals). F-strings provide a concise and convenient way to embed expressions inside string literals, making it easier to format and interpolate variables into strings.
To create an f-string, you prefix the string with the letter ‘f’ or ‘F’ and enclose the variables or expressions you want to include within curly braces {}.
Here’s an example that demonstrates the usage of f-strings:
1 2 3 4 5 6 |
name = "Alice" age = 25 occupation = "engineer" greeting = f"Hello, {name}! You are {age} years old and work as an {occupation}." print(greeting) |
Output
Hello, Alice! You are 25 years old and work as an engineer.
In the above example, the variables name
, age
, and occupation
are included within the f-string by placing them inside curly braces {}. The values of these variables are then interpolated into the string when it is printed.
You can also perform operations or call functions inside the curly braces. Here’s another example that demonstrates this:
1 2 3 4 5 |
x = 10 y = 5 result = f"The sum of {x} and {y} is {x + y}." print(result) |
Output
The sum of 10 and 5 is 15.
In the above example, the expression {x + y}
evaluates to 15
and is inserted into the f-string.
F-strings provide a powerful way to create dynamic and formatted strings by directly embedding variables and expressions. They offer a concise and readable alternative to other string formatting methods in Python.
Concatenating Python strings
You can concatenate two strings using the +
operator. The +
operator allows you to combine multiple strings into a single string.
1 2 3 4 |
greeting = "Hello" name = "John" message = greeting + ", " + name print(message) # Output: Hello, John |
You can concatenate any number of strings using the +
operator. Here’s another example that concatenates three strings:
1 2 3 4 5 |
greeting = "Welcome" name = "John" suffix = "!" message = greeting + ", " + name + suffix print(message) |
Output
Welcome, John!
In this example, the three strings greeting
, name
, and suffix
are concatenated using the +
operator, along with the comma and exclamation mark.
It’s important to note that when concatenating strings, you can only concatenate strings with strings. If you want to concatenate a string with a non-string value, you need to convert the non-string value to a string first. This can be done using the str()
function.
Here’s an example that demonstrates concatenating a string with a non-string value:
1 2 3 |
number = 25 text = "The answer is: " + str(number) print(text) |
Output
The answer is: 25
In this example, the number
variable is converted to a string using the str()
function before concatenating it with the string “The answer is: “.
Concatenating strings using the +
operator provides a simple and straightforward way to combine multiple strings in Python.
Getting the length of a string
You can find the length of a string using the len()
function.The len()
function returns the number of characters in a string, including whitespace, special characters, and punctuation marks.
Example 1
1 2 3 |
text = "Python" length = len(text) print(length) # Output: 6 |
Example 2
1 2 |
text = "Hello, world!" print(len(text)) # Output: 13 |
Indexing and Slicing of the String
You can access individual characters or a substring within a string using indexing and slicing.
Indexing:
Indexing allows you to access a specific character in a string by referring to its position, or index. In Python, indexing starts from 0 for the first character, and you can use positive or negative indices to access characters from the beginning or end of the string, respectively.
Here’s an example that demonstrates indexing:
1 2 3 4 5 |
text = "Hello, world!" print(text[0]) # Output: H print(text[7]) # Output: w print(text[-1]) # Output: ! |
In the above example, text[0]
returns the first character ‘H’, text[7]
returns the character ‘w’, and text[-1]
returns the last character ‘!’.
Slicing:
Slicing allows you to extract a portion, or a slice, of a string by specifying a range of indices. It is denoted by the colon (:) operator. The slice includes the character at the starting index and goes up to, but does not include, the character at the ending index.
Here’s an example that demonstrates slicing:
1 2 3 4 5 6 |
text = "Hello, world!" print(text[0:5]) # Output: Hello print(text[7:12]) # Output: world print(text[:5]) # Output: Hello (omitting the starting index is equivalent to starting from the beginning) print(text[7:]) # Output: world! (omitting the ending index is equivalent to going until the end) |
In the above example, text[0:5]
returns the substring ‘Hello’, text[7:12]
returns ‘world’, text[:5]
returns ‘Hello’, and text[7:]
returns ‘world!’.
String Methods
Python provides a variety of built-in methods that you can use to manipulate and perform operations on strings. Here are some commonly used string methods:
upper()
and lower()
: These methods convert a string to uppercase or lowercase, respectively.
1 2 3 |
text = "Hello, World!" print(text.upper()) # Output: HELLO, WORLD! print(text.lower()) # Output: hello, world! |
capitalize()
: This method capitalizes the first character of a string and converts the rest to lowercase.
text = “hello, world!”
print(text.capitalize()) # Output: Hello, world!
split()
: This method splits a string into a list of substrings based on a specified separator (default is whitespace).
1 2 3 |
text = "Hello, World!" words = text.split(", ") print(words) # Output: ['Hello', 'World!'] |
join()
: This method joins the elements of an iterable (e.g., a list) into a string using a specified separator.
1 2 3 |
words = ['Hello', 'World!'] text = ", ".join(words) print(text) # Output: Hello, World! |
replace()
: This method replaces all occurrences of a specified substring with another substring.
1 2 3 |
text = "Hello, World!" new_text = text.replace("World", "Python") print(new_text) # Output: Hello, Python! |
startswith()
and endswith()
: These methods check if a string starts or ends with a specified substring and return a boolean value.
1 2 3 |
text = "Hello, World!" print(text.startswith("Hello")) # Output: True print(text.endswith("!")) # Output: False |
These are just a few examples of the many string methods available in Python. You can find more string methods in the official Python documentation (https://docs.python.org/3/library/stdtypes.html#string-methods) and explore them based on your specific requirements.
Python strings are immutable
Strings are immutable in Python, which means that once a string is created, its contents cannot be changed. You cannot modify individual characters within a string or replace characters in-place.
However, you can perform operations on strings that create new strings as a result. For example, concatenating two strings with the +
operator creates a new string without modifying the original strings.
Here’s an example to illustrate the immutability of strings:
1 2 3 4 |
text = "Hello" new_text = text + ", world!" # Concatenation creates a new string print(new_text) # Output: Hello, world! print(text) # Output: Hello |
In the above example, the original string text
remains unchanged, and a new string new_text
is created by concatenating text
with “, world!”.
If you attempt to modify a string directly, you’ll encounter a TypeError
:
1 2 |
text = "Hello" text[0] = "T" # Raises TypeError: 'str' object does not support item assignment |
Attempting to modify the first character of text
by assigning “J” to text[0]
results in a TypeError
because strings are immutable.
To change the contents of a string, you need to create a new string with the desired modifications. This can be done using various string manipulation methods or by creating new strings through concatenation, slicing, or string formatting.
The immutability of strings in Python is intentional and brings benefits such as improved performance and the ability to use strings as dictionary keys. However, if you need a mutable string-like data structure, you can use a list of characters instead. Lists are mutable and can be modified by changing individual elements.