In Python, a string refers to a sequence of characters. String is particularly useful when you’re dealing with textual data in Python.
In this tutorial, we’ll walk through some Python string basics, the most commonly used Python string methods, and a multitude of ways to convert Python methods into strings. We will specifically look at converting Python list to string, Python int to string, Python bytes to string, and finally, Python datetime to string.
Table of Contents
- Python String Overview
- Python String Methods
- Convert Python List to String
- Convert Python int to String
- Convert Python Bytes to String
- Convert Python Datetime to String
- Wrap Up
- References
Python String Overview
Creating a Python string
To create a Python string, you can enclose characters with single quote, double quotes, or triple quotes. While triple quotes can be used for single line strings, it’s most useful for multiline strings and docstrings. Additionally, depending on the complexity of your code, you can name your strings according to best practices:
my_string = 'Codementor'
print(my_string)
my_string = "Codementor"
print(my_string)
my_string = '''Codementor'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Welcome to Codementor,
find a Python expert to help you learn Python!"""
print(my_string)
Output:
Codementor
Codementor
Codementor
Welcome to Codementor,
find a Python expert to help you learn Python!
💡Tip: You can name your Python string anything! Instead of my_string
, we’ll simply name our Python string s
in the next section.
Accessing characters in a Python string
Each character in a Python string is assigned an index, and the index starts with 0 and must be an integer. There are two ways of accessing the characters: (1) using positive integers, and (2) using negative integers.
For negative indexes, the index of -1
refers to the last item, -2 to the second last item, and so on. If you want to access a range of items in a string, you can use the slicing operator, :
.
Here’s an illustration to help you understand how the positive and negative indexes work in a Python String:
Once, again, using “Codementor” as an example:
s = 'Codementor'
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
print(s[6])
print(s[7])
print(s[8])
print(s[9])
Output:
C
o
d
e
m
e
n
t
o
r
To get the same output, you'd use negative integers this way:
s = 'Codementor'
print(s[-10])
print(s[-9])
print(s[-8])
print(s[-7])
print(s[-6])
print(s[-5])
print(s[-4])
print(s[-3])
print(s[-2])
print(s[-1])
You can also access multiple characters from the Python string. For instance:
s = 'Codementor'
print(s[:])
print(s[:4])
print(s[-6:])
print(s[2:5])
Output:
Codementor
Code
mentor
dem
Now you know the basics of how to work with Python strings, let's talk about some of the most widely used Python string methods.
Python String Methods
To allow developers to work with Python strings quicker, there are built-in shortcuts to manipulate the output of the string. These shortcuts are called Python string methods. A Python string method does not change the original string. Instead, it is used to return new values.
The most commonly used Python string methods include capitalize()
, lower()
, upper()
, join()
, split()
, find()
, and replace()
. Python format()
is another powerful and frequently used Python string method. However, due to its complexity, we will not cover it here. Feel free to learn more about format()
from Python’s official documentation!
We'll run through the seven Python string methods and include a table of all the Python string methods at the end of the tutorial.
capitalize()
Python string method
The capitalize()
string method is used when you want to capitalize the first character of a string of text. Here’s an example:
s = "codementor speeds up your python learning process"
x = s.capitalize()
print (x)
Output:
Codementor speeds up your python learning process
lower()
Python string method
lower()
Python string method is the opposite of upper()
. It turns all of the characters in a string into lowercase letters.
s = "CODEMENTOR HELPS solve your CODING problems!"
x = s.lower()
print(x)
Output:
codementor helps solve your coding problems!
upper()
Python string method
upper()
Python string method is the opposite of lower()
. It turns all of the characters in a string into uppercase letters.
s = "codementor has the best python tutors!"
x = s.upper()
print(x)
Output:
CODEMENTOR HAS THE BEST PYTHON TUTORS!
(We really do have the best Python mentors and tutors!)
join()
Python string method
The join()
method takes all items in an iterable and joins them into one string. For example, you can join items in a tuple or in a dictionary. Let’s say you want to put all your party guests’ into a string, you can use the following code and join()
method to combine and create the list.
PartyGuests = ("Anna", "Allie", "Joy", "Chloe", "Ellyn")
x = ", ".join(PartyGuests)
print(x)
Output:
Anna, Allie, Joy, Chloe, Ellyn
split()
Python string method
The split()
method splits a Python string into a list. You can specify the separator, but the default separator is any whitespace.
Here’s an easy example to help you understand how split()
works:
txt = "Find Python Help on Codementor Today"
x = txt.split()
print(x)
Output:
['Find', 'Python', 'Help', 'on', 'Codementor', 'Today']
Usually, split()
divides a Python string in a list into single items. However, you may split the string into a list with a maximum of 2 items. Here’s how that could work, using # as the separator:
txt = "best#way#to#learn#python#is#to#find#a#mentor"
x = txt.split("#", 5)
print(x)
The output would look something like this funny list:
['best', 'way', 'to', 'learn', 'python', 'is#to#find#a#mentor']
find()
Python string method
The find()
method is used to find a specified value’s first appearance in a string. It is almost identical to the index()
method, except when a value cannot be found. Instead of displaying -1
, the index()
method displays ValueError: substring not found
.
Let’s use “Codementor” for this one:
txt = "Codementor"
x = txt.find("e", 4, 8)
print(x)
When you run the code above, you’ll get the output 5
. Normally, find()
would find the first appearance of “e” in the string, which would be 3 in our example. However, in the example above, it asked for “e” between position 4 and 8, which is why our output is 5
.
replace()
Python string method
The replace()
method is used to replace a specified phrase with another specified phrase. Unless otherwise specified, all specified phrases in the Python string will be replaced.
Let’s see a simple example of replace()
:
str = "I love office work because office work is the best."
x = str.replace("office", "remote")
print(x)
See what we did there? Instead of “I love office work”, we now have:
I love remote work because remote work is the best
I mean...who doesn’t love remote work?
Now, let’s see how we would work with replace()
if we only want to replace one of the words in a Python string:
str = "I love office work but going into the office to bond with my colleagues can be fun!"
x = str.replace("office", "remote", 1)
print(x)
Output:
I love remote work but going into the office to bond with my colleagues can be fun!
There are two “office” in the string, but we only want to replace the first “office” with “remote”. By adding the 1
, we’ve replaced the first occurrence of the word “office.”
Now, there are lots of Python string methods you can use to manipulate the outcome of any given Python string but we won’t cover all of them in depth in this article. As format()
is an extremely important and super powerful Python string method, we will dedicate another article to format()
. You can find a list of all the Python string methods in the reference section!
⚠️ Note: Make sure to check if the Python string methods listed below work with the Python version you’re working with!
Convert Python List to String
Before we jump into the different ways we can convert a Python list to string, let’s briefly run through what a list is and two different types of lists.
If you’re familiar with other programming languages, a list in Python is equivalent to an array. A Python list is encased by square brackets, while a comma(,) is used to separate objects in the list. The main difference between an array and a Python list is that arrays usually contain homogenous objects while Python lists can contain heterogeneous objects.
Homogenous list:
list=[‘a’,’b’,’c’]
list=[‘America’,’India’,’Taiwan’]
list=[1,2,3,4,5]
Heterogeneous list:
list=[2,"America",5.2,"b"]
There are four ways to convert Python list to string:
- Using
join()
Python string method - Using List Comprehension along with
join()
Python string method - Using
map()
Python string method - Using iteration through for loop
We will go through each of these methods:
Python list to string using join()
method
The join()
method can create strings with iterable objects. The element of an iterable (i.e. list, string, and tuple) can be joined by a string separator to return a new concatenated string.
Syntax: string.join(iterable)
And here’s an example of turning a Python list to string:
inp_list = ['Coding', 'for', 'Everyone']
out_str = " "
print(out_str.join(inp_list))
Output:
Coding for Everyone
Python list to string using list comprehension along with join()
Now, using the join()
method to convert a Python list to string works as long as the passed iterable contains string elements. However, if the list contains both string and integer as its element, we’d need to convert elements to string while adding to string. This is where using list comprehension along with join()
comes in handy.
from builtins import str
inp_list = ['There', 'are', 'more', 'than', 10000, 'mentors', 'who', 'can', 'help', 'you', 'learn', 'Python', 'on', 'Codementor']
listToStr = ' '.join([str(elem) for elem in inp_list])
print(listToStr)
Output:
There are more than 10000 mentors who can help you with Python on Codementor
Python list to string using map()
function
Similar to the string()
method, the map()
function accepts functions and iterable objects, like lists, types, strings, etc. The map()
function maps the elements of the iterable with the function provided.
Syntax for map(): map(function, iterable)
The iterables are seen as arguments in map() functions. With the map()
function, every element of the iterable (list) is mapped onto a given function to generate a list of elements. We’ll then use the join()
method to display the output in string form:
inp_list = ['Get', 'Python', 'help', 'in', 'less', 'than', 6, 'minutes', 'on', 'Codementor']
listToStr = ' '.join(map(str, inp_list))
print(listToStr)
Output:
Get Python help in less than 6 minutes on Codementor
Python list to string using iteration through for loop
To convert a Python list to string using for loop, the elements of the input list are iterated one by one and added to a new empty string.
Here’s how it’d work:
# Function to convert
def listToString(s):
out_str = ""
# traverse in the string
for ele in inp_str:
out_str += ele
# return string
return out_str
# Driver code
inp_str = ['Codementor', 'is', 'AWESOME']
print(listToString(inp_str))
Output:
CodementorisAWESOME
Convert Python int to String
Converting Python int to string is a lot more straightforward than converting Python list to string: you just have to use the built-in str()
function. With that said, there are four ways of converting Python int to string. The examples we provide below apply to Python 3.
- Using the
str()
function - Using “%s” keyword
- Using
.format()
function - Using f-string
Python int to string using the str()
function
Syntax: str(integer_value)
The code is relatively simple and straightforward:
num = 100
print(type(num))
converted_num = str(num)
print(type(converted_num))
Python int to string using “%s” keyword
Syntax: “%s” % integer
num = 100
print(type(num))
converted_num = "% s" % num
print(type(converted_num))
Python int to string using .format()
function
Syntax: ‘{}’.format(integer)
num = 100
print(type(num))
converted_num = "{}".format(num)
print(type(converted_num))
Python int to string using f-string
⚠️ Note: This method may not work for Python 2.
Syntax: f'{integer}’
num = 100
print(type(num))
converted_num = f'{num}'
print(type(converted_num))
Converting Python int to string is simple but it is extremely useful in a greater context. Here’s an example of how the above methods of converting Python int to string may appear in real-world scenarios. Let’s say you want to print an output of how many Python mentors you’ve worked with on Codementor:
mentor_count = 30
print(type(mentor_count))
converted_num = str(mentor_count)
print("The number of mentors I have worked with in the last month: " + str(mentor_count))
Output:
<class ‘int’>
The number of mentors I have worked with in the last month: 30
Convert Python Bytes to String
Converting Python bytes to string is really about decoding and reverting a set of bytes back into a Unicode string. For example, decoding the byte string "\x61\x62\x63" and reverting it back to UTF-8 will give you "abc".
There are 3 ways to convert Python bytes to string:
- Using
decode()
method - Using
str()
function - Using
codec.decode()
method
Python bytes to string using decode()
method
The decode()
method allows developers to convert an argument string from one encoding scheme to another.
import string
data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = data.decode()
print('\nOutput:')
print(output)
print(type(output))
Output:
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
Python bytes to string using str()
function
The str()
function of Python returns the string version of the object.
data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = str(data, 'UTF-8')
print('\nOutput:')
print(output)
print(type(output))
Output:
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
Python bytes to string using codec.decode()
method
import codecs
data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = codecs.decode(data)
print('\nOutput:')
print(output)
print(type(output))
Output:
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
Convert Python Datetime to String
Converting datetime class objects to Python string is not difficult with the datetime.strftime()
function. What is tricky is that there are many different ways to showcase datetime, thus presenting developers the challenge of knowing when to use what format code.
Python datetime to string for current time
Using the datetime.strftime()
function, you can turn the current datetime object into different string formats:
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
At the time of writing, this is the output:
year: 2021
month: 07
day: 09
time: 05:22:21
date and time: 07/09/2021, 05:22:21
Python datetime to string from timestamp
Now, if you need to convert Python datetime to string based on a timestamp you’re given, the code would look different. Here’s an example of how a timestamp could be converted to different string formats.
from datetime import datetime
timestamp = 1625834088
date_time = datetime.fromtimestamp(timestamp)
print("Date time object:", date_time)
d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("Date and time:", d)
d = date_time.strftime("%d %b, %Y")
print("Shortened date:", d)
d = date_time.strftime("%d %B, %Y")
print("Full date:", d)
d = date_time.strftime("%I%p")
print("Hour of day:", d)
Output:
Date time object: 2021-07-09 12:34:48
Date and time: 07/09/2021, 12:34:48
Shortened date: 09 Jul, 2021
Full date: 09 July, 2021
Hour of day: 12PM
Python datetime to string format codes
In the example above, a lot of format codes were used to display datetime in different ways. Some of the format codes—%m, %d, %Y—are more intuitive than others. Don’t worry. Even the best Python developers have to look up format codes when they code! We’ve attached all the format codes in the references section.
With the format codes, you can manipulate your timestamp into any Python string format you’d like!
Wrap Up
Python String is a fundamental part of working with Python. While this tutorial covered some of the basics of Python String—including some Python string methods and different ways to convert Python list, int, bytes, and datetime to strings—there is a lot more to Python strings. Python is a relatively friendly language for beginners. However, if you want to lay a more solid foundation while speeding up your learning, working with a Python tutor would be key. Additionally, working on some Python projects to bridge the gap between theory and real-world application would help solidify the concepts we ran through in this tutorial!
If you found this tutorial helpful, like and share it with those you think would benefit from reading it! Comment below to let us know what you think about the tutorial 🤓
References
Table of Python String Methods
Python String Method | Description |
---|---|
casefold() | Similar to lower() , Converts string to lower cases. |
center() | Centers the string output. |
count() | Count how many times a variable appeared in a string. |
encode() | Encodes the string, using the specified encoding. If unspecified, UTF-8 will be used. |
endswith() | Returns true if the string ends with the specified value. |
expandtabs() | Uses \t to create spaces between characters. |
format() | Formats specified values in a string. |
format_map() | Similar to format()
|
index() | Searches the string for a specified value and returns the position of where the value is. If the value is a word in a string of sentence, the index will be the number of the first character of the word. |
isalnum() | Returns True if all characters in the string are alphabets and numeric. If there’s a space in the string, you’d get False. |
isalpha() | Returns True if all the characters in the string are in the alphabet. Characters like ë are considered alphabets. Applies to all languages. |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier. Identifiers can only contain alphanumeric letters or underscores. An identifier can’t start with a number, or contain any spaces. |
islower() | Returns True if all characters are lowercase. |
isnumeric() | Returns True if all characters are numeric. |
isprintable() | Returns True if all characters in the string are printable. |
isspace() | Returns True if all characters are whitespaces. |
istitle() | Returns True if the string follows the rules of a title, which means all words start with an uppercase letter and the rest are lowercase letters. |
isupper() | Returns True if all characters in the string are upper case. |
ljust() | Left aligns the specified string characters and uses numbers to indicate the amount of space to separate specified variables from other characters or sentences. |
maketrans() | Used to replace characters with specified characters. |
partition() | Searches for a specified string, and splits the string into a tuple containing three elements. The specified element will be the second element, and the first and third will be what comes before and after the specified element. |
replace() | Replaces the specified value in the string with another specified value in the new string. |
rfind() | Searches the string for a specified value and returns the last position of where it was found. The index will be the number of the first character of the specified value. |
rindex() | Searches the string for a specified variable and returns the last position of where it was found. The index will be the number of the first character of the specified variable. |
rjust() | Returns a right justified version of the string. Opposite of ljust() . |
rpartition() | Similar to partition() . |
rsplit() | Splits a string into a list, starting from the right. If no "max" is specified, this method will return the same as the split() method. |
rstrip() | Removes any spaces or trailing characters that are specified. |
split() | Splits a string into a list. The default separator is any whitespace, but the separator can be specified (i.e. , ). |
splitlines() | Uses \n to split the string into a list. |
startswith() | Returns True if the string starts with the specified value. |
strip() | Removes any leading and trailing characters of the specified variables. Unless otherwise specified, the default trailing characters are whitespaces. |
swapcase() | Swaps all the characters in a string. If the character is an uppercase letter, it’ll turn into a lowercase letter, and vice versa. |
title() | Converts the first character of each word to uppercase. |
translate() | Returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. |
zfill() | Adds zeros (0) at the beginning of the string, until it reaches the specified length. |
Table of Format Codes
Format Code | Description | Example |
---|---|---|
%d | Day of the month as zero-padded numbers | 01, 02, 03, 04 …, 31 |
%a | Abbreviated weekday | Sun, Mon, Wed, ..., Sat |
%A | Full weekday name | Sunday, Monday, …, Saturday |
%m | Month as zero-padded numbers | 01, 02, 03, …, 12 |
%b | Abbreviated month | Jan, Feb, … Dec |
%B | Full month name | January, February, …, December |
%y | Year without century | 00, 01, 02, …, 99 |
%Y | Year with century | 0001, …, 2021, …, 9999 |
%H | 24-hr clock hour | 01, 02, 03, …, 23 |
%M | Minute as zero-padded numbers | 01, 02, …, 59 |
%S | Second as zero-passed numbers | 01, 02, …, 59 |
%f | Microsecond, zero-padded on the left | 000000, 000001, …, 999999 |
%l | 12-hr clock hour | 01, 02, …, 12 |
%p | Location’s AM or PM | AM, PM |
%j | Day of the year | 01, 02, 03, …, 366 |