- Python Strings
- Example
- Assign String to a Variable
- Example
- Multiline Strings
- Example
- Example
- Strings are Arrays
- Example
- Looping Through a String
- Example
- String Length
- Example
- Check String
- Example
- Example
- Check if NOT
- Example
- Example
- Python Strings — The Definitive Guide
- How to create strings in Python?
- How to access characters in a Python string?
- String Slicing
- How to replace characters in a string in Python?
- Can you replace characters in a string in Python?
- Method 1 — Python string replace() method
- Method 2 — Python list() method
- Concatenating strings in Python
- How to iterate through a string in Python?
- Check if a Substring is Present in a Given String in Python
- Method 1 — Using in and not in keywords
- Method 2 — Python String find() Method
- Method 3 — Python String count() Method
- Escape sequences in Python String
- Other Escape Sequences in Python
- Related Articles
- Subscribe to Pylenin
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
‘hello’ is the same as «hello» .
You can display a string literal with the print() function:
Example
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = «»»Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.»»»
print(a)
Example
a = »’Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.»’
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word «banana»:
Learn more about For Loops in our Python For Loops chapter.
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in .
Example
Check if «free» is present in the following text:
Use it in an if statement:
Example
Print only if «free» is present:
Learn more about If statements in our Python If. Else chapter.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in .
Example
Check if «expensive» is NOT present in the following text:
Use it in an if statement:
Example
print only if «expensive» is NOT present:
Python Strings — The Definitive Guide
Strings are amongst the most popular data types in Python. A string can be defined as a sequence of characters.
How to create strings in Python?
Strings can be created by enclosing characters inside a single quote, double-quotes, and triple quotes.
Code
# Single Quotes my_string = 'Pylenin' print(my_string) # Double Quotes my_string = "Pylenin" print(my_string) # Triple Quotes # can be extended over multiple lines my_string = """Check out Pylenin for Python related blogs and videos""" print(my_string)
Output
Pylenin Pylenin Check out Pylenin for Python related blogs and videos
As you can see in the code above, we are assigning a string to a variable. It is done with the variable name followed by an equal sign and the string.
Unless necessary, try not to use triple quotes for strings. It is generally used for writing docstrings in your Python code, which acts like a documentation.
How to access characters in a Python string?
You can access individual characters of a string through string indexing and a range of characters using slicing.
In Python, the index starts from 0 and keeps increasing by 1 with every character. This is called Positive Indexing (or indexing from the beginning). If there are n characters in a string, the 1st character will be index 0 and the last character will have index n-1.
Let’s look at the image below for a better understanding.
Python also allows negative indexing(indexing from the end). If there are n characters in a string, the last character will have an index of -1 and the first character will have an index of -n.
Let’s look at the image below for a better understanding.
Code
str = 'PYLENIN' # first character print('str[0] =', str[0]) # last character print('str[-1] =', str[-1]) # second character print('str[1] =', str[1]) # second last character print('str[-2] =', str[-2])
Output
str[0] = P str[-1] = N str[1] = Y str[-2] = I
If you try to access a character out of range, it will raise an IndexError .
Also, the index must be an integer. You can’t use floats or other types for indexing. This will result in TypeError .
Code/Output
str = 'PYLENIN' print(str[10]) >>> IndexError: string index out of range print(str[1.5]) >>> TypeError: string indices must be integers
String Slicing
To access a range of characters, you need to use slicing. Basically, you have to specify the start index and the end index, separated by a colon, to return a part of the string.
Remember — The last index is not included.
Let’s say you want to access all the elements from the 2nd index to the 4th index of PYLENIN string. In that case, your end index will be 5.
Code
str = 'PYLENIN' # 2nd to 4th index print('str[2:5] =', str[2:5])
Output
If you leave out the start index, the range will start at the first character. This is the same as mentioning the start index as 0.
Code
str = 'PYLENIN' # 2nd to 4th index print('str[:5] =', str[:5])
Output
If you leave out the end index, the range will go to the end.
Code
str = 'PYLENIN' # 2nd to 4th index print('str[2:] =', str[2:])
Output
Check out the code below. Both the statements produce the same result.
str = 'PYLENIN' print('str[2:5] =', str[2:5]) print('str[-5:-2] =', str[-5:-2])
Output
How to replace characters in a string in Python?
Can you replace characters in a string in Python?
In Python, strings are immutable.
This means elements of a string cannot be changed or replaced once they have been assigned.
Code
Output
Traceback (most recent call last): File "file_location", line 2, in x[0] = "L" TypeError: 'str' object does not support item assignment
However, we can certainly create a copy of our string with our necessary replacements.
Method 1 — Python string replace() method
The replace() method replaces a specified character/phrase with another.
Syntax of replace()
string.replace(oldstring, newstring, count) oldstring - The string to replace(required) newstring - The string to replace with(required) count - A number specifying how many occurrences of the old value you want to replace. Default is all occurrences (optional)
Example 1
Replace all occurrences of the word Pylenin .
Code
txt = "I like Pylenin" x = txt.replace("Pylenin", "Python") print(x)
Output
Example 2
Replace the first two occurrences of the word Python .
Code
txt = "Python is the best. " \ "I love Python. " \ "I enjoy Python" x = txt.replace("Python", "Pylenin", 2) print(x)
Output
Pylenin is the best. I love Pylenin. I enjoy Python
Method 2 — Python list() method
Another solution would be to convert a string to a python list and then make necessary changes. Unlike Python strings, Python lists are mutable.
Code
old_str = "foofoo" str_list = list(old_str) str_list[0] = 'd' new_string = "".join(str_list) print(new_string)
Output
Concatenating strings in Python
Concatenation is the process of joining of two or more strings into a single string.
In Python, the + operator is used for concatenation. You can also concatenate two strings by writing them together. Another way is to use the * operator to repeat the string for a given number of times.
Code
str1 = "I like " str2 = "Pylenin" print(str1+str2) print(str1, str2) print(str1*2)
Output
I like Pylenin I like Pylenin I like I like
How to iterate through a string in Python?
We can iterate or loop through a string in Python by using the for loop.
Code
str1 = "Pylenin" for letter in str1: print(letter)
Output
Check if a Substring is Present in a Given String in Python
Given two strings, check if s1 is present in s2 .
Method 1 — Using in and not in keywords
Code
s2 = "I like Pylenin" s1 = 'like' print(s1 in s2) print(s1 not in s2)
Output
Method 2 — Python String find() Method
The find() method in Python finds the first occurrence of a specified value in a given string. It returns the index where the substring s1 occurs. It returns -1 if the value is not found.
The find() method is similar to the index() method. Only difference — index() method raises an exception if the value is not found.
Code
s2 = "I like Pylenin" s1 = 'like' print(s2.find(s1))
Output
The above result tells us that the like substring first occurs at the 2nd index.
Let’s check for another substring.
Code
s2 = "I like Pylenin" s1 = 'Python' print(s2.find(s1))
Output
The above result tells us that the substring Python doesn’t exist in s1 .
Method 3 — Python String count() Method
The count() method returns the number of times a substring s1 appears in the string s2 . It is not case-sensitive.
Syntax
string.count(value, start, end) value: The substring to search for(required) start: The integer position to start the search. Default is 0.(Optional) end: The integer position to end the search. Default is the end of the string.(Optional)
Code
s2 = "I like Pylenin" s1 = 'like' if s2.count(s1) > 0: print(f"'' exists in ''")
Output
'like' exists in 'I like Pylenin'
Let’s search for a non-existing string.
Code
s2 = "I like Pylenin" s1 = 'Python' if s2.count(s1) > 0: print(f"'' exists in ''") else: print(f"'' doesn't exist in ''")
Output
'Python' doesn't exist in 'I like Pylenin'
Let’s now search a substring s1 in a specific portion of string s2 .
Code
s2 = "I like reading Pylenin blogs on Python" s1 = 'Python' # Search between position 10 and 20 if s2.count(s1, 10, 20) > 0: print(f"'' exists in ''") else: print(f"'' doesn't exist in ''") print(s2.find(s1))
Output
'Python' doesn't exist in 'I like reading Pylenin blogs on Python' 32
As you can see, the substring Python doesn’t occur between positions 10 and 20. The find() method shows that it occurs at position 32.
Escape sequences in Python String
Escape sequences or Escape characters in Python, are used to insert characters that are illegal in a string.
Here is an example of an illegal character in a Python string.
Example1 - "Pylenin said, "Hi there"" Example2 - 'Pylenin said, 'Hi there''
In Example 1, we have double quotes inside double quotes. In Example 2, we have single quotes inside of single quotes. These qualify as illegal characters in a string.
If we try to print it, Python will throw us a SyntaxError .
One way to fix this is by using Escape characters or sequences.
If we are using single quotes to represent a string, all the single quotes inside the string must be escaped with a \ character.
Similarly, if we are using double quotes to represent a string, all the double quotes inside the string must be escaped with a \ character. .
Code
str1 = "Pylenin said, \"Hi there\"" print(str1) str2 = 'Pylenin said, \'Hi there\'' print(str2)
Output
Pylenin said, "Hi there" Pylenin said, 'Hi there'
Other Escape Sequences in Python
Escape Sequence | Description |
---|---|
\newline | Backslash and newline ignored |
\ | Backlash |
‘ | Single Quote |
« | Double Quote |
\a | ASCII Bell |
\b | ASCII Backspace |
\f | ASCII Formfeed |
\n | ASCII Linefeed |
\r | ASCII Carriage Return |
\t | ASCII Horizontal Tab |
\v | ASCII Vertical Tab |
\ooo | Character with octal value ooo |
\xHH | Character with hexadecimal value HH |
Hope you enjoyed this article on Python Strings. In case of any doubts or suggestions, connect with me on Twitter.
Related Articles
Subscribe to Pylenin
Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.