January 24, 2023

Python strings – Complete tutorial

Share this

By Andrei Maksimov

June 28, 2021

contain, conversion, find, length, python-course, replace, reverse, split, startswith, string, substring

Enjoy what I do? Consider buying me a coffee ☕️

Python is a well-known dynamically initialized, interpreted, and object-oriented high-level programming language. It’s a convenient and possibly the best language that minimizes software maintenance expenses in the long run. In addition, it is probably the number one choice if you’re busy with cloud automation tasks. This article illustrates the most commonly used Python string operations, such as concatenation, type conversion, split, replace, search, and trim.

String concatenation

Combining or merging strings is a regular operation that you’ll see in almost any Python code. String concatenation is the term for describing those activities.

The most straightforward and popular way to combine multiple strings into a single object is to use the plus (+) operator, for example:

result = 'Python' + ' for' + ' cloud' + ' automation'
print(result)
1. Python - The most commonly used string operations - String concatenation - Example 1

It’s worth mentioning that Python can’t combine a string and an integer. If you try to do that, you’ll get the following error message “TypeError: can only concatenate str (not “int”) to str“.

To combine them, you must first change the number to a string, for example:

message = "I'm" + str(34) + " years old"
print(message)
2. Python - The most commonly used string operations - String concatenation - Example 2

Type conversion

What you saw in the previous example is called type conversion. Python has several built-in functions, which allow you to convert strings to other data types, and back.

Int to str

Using Python’s str() function to convert an integer to a string:

my_string = str(34)
type(my_string)
print(string)
3. Python - The most commonly used string operations - String type conversion - Int to str

Str to int

To convert Python strings to integers, you have to use the int() built-in function:

integer = int("22")
print(type(integer))
print(integer)
4. Python - The most commonly used string operations - String type conversion - str to int

List to str

In Python, you have to use the join() function to convert a list to a string:

my_list = ['Welcome', 'to', "'Quick", 'intro', 'to', 'Python', '3', 'for', 'AWS', 'automation', "engineers'", 'course']
print(my_list)
' '.join(my_list)
5. Python - The most commonly used string operations - String type conversion - list to str

Str to float

To convert a string to a float in Python, use the float() method:

my_string = "7.68"
my_float = float(my_string)
print(type(my_float))
print(my_float)
6. Python - The most commonly used string operations - String type conversion - str to float

Split string (str to list)

To split strings in Python, we have the split() function that can be used to split sentences into the list of strings: 

my_string = "Welcome to 'Quick intro to Python 3 for AWS automation engineers' course"
my_list = my_string.split(' ')
print(type(my_list))
print(my_list)
8. Python - The most commonly used string operations - String type conversion - str to list

You can use any delimiter in the split() function, for example:

my_ip = "192.162.1.1"
octets = my_ip.split('.')
print(octets)
9. Python - The most commonly used string operations - String type conversion - str to list (ip address split)

Str to datetime

Python’s standard library provides us with the datetime module, which defines date, time, timezone, and other classes that can be used to do date and time-related operations.

Here are some definition examples:

from datetime import (
    date,
    time,
    datetime
)
dateobject = date(y, m, d)
timeobject = time(h, m, s)
datetimeobject = datetime(y, m, d, h, m, s)

Now, let’s take a look at how to convert string to datetime object:

strdate="2021-06-10 07:35:20"
dt_tuple=tuple([int(x) for x in strdate[:10].split('-')])+tuple([int(x) for x in strdate[11:].split(':')])
datetimeobject = datetime(*dt_tuple)
print(type(datetimeobject))
print(datetimeobject)
7. Python - The most commonly used string operations - String type conversion - str to datetime

Replace string

To replace a part of the string in Python, we have a built-in replace() function that returns a string where all instances of a substring are replaced with another substring:

my_string = "Welcome to 'Quick intro to Python 3 for AWS automation engineers' course"
new_string = my_string.replace("Python 3", "Python 3.9")
print(new_string)
10. Python - The most commonly used string operations - String type conversion - replace substring

Substrings lookup

Several methods in Python can be used to look up a substring in a given string.

Let’s take a look at the most commonly used ones.

In statement

The easiest and most common way to check if a string contains a substring in Python is to use in operator in if-conditional expression:

course_name = "Welcome to 'Quick intro to Python 3 for AWS automation engineers' course"
if 'AWS' in course_name:
    print("This course is about AWS")
11. Python - The most commonly used string operations - String type conversion - Substring lookup - in statement

Startswith

Python’s startswith() function determines if the string begins with a given substring:

course_name = "Quick intro to Python 3 for AWS automation engineers"
if course_name.startswith('Quick'):
    print('This is a quick course')
12. Python - The most commonly used string operations - String type conversion - Substring lookup - startswith

Find

In Python, you can use the find() built-in function that returns the index of the first instance of a substring in a string. If the desired substring is not found in the given string, the find() function will return -1 instead of generating an exception:

course_name = "Quick intro to Python 3 for AWS automation engineers"
word = 'intro'
position = course_name.find(word)
if position != -1:
    print(f"'{word}' found at position {position}")
else:
    print(f"'{word}' not found")
13. Python - The most commonly used string operations - String type conversion - Substring lookup - find

String length

To determine string length in Python, you can use the len() built-in function:

course_name = "Quick intro to Python 3 for AWS automation engineers"
course_name_length = len(course_name)
print(f'Course name is {course_name_length} characters')
14. Python - The most commonly used string operations - String type conversion - String length

Reverse string

If you need to reverse a string (flip characters in the string in reversed order), use the reverse() function:

my_string = "0123456789"
reversed_string = ''.join(reversed(my_string))
print(reversed_string)
15. Python - The most commonly used string operations - String type conversion - Reversed string

Trim string

If you need to remove white space characters at the beginning and end of the string, you can use the strip() built-in Python function.

All leading and trailing whitespace characters, such as \n, \r, \t, \f, and spaces will be removed using the Python strip() method:

course_name = "    Quick intro to Python 3 for AWS automation engineers    "
course_name = course_name.strip()
print(f"Result: '{course_name}'")
16. Python - The most commonly used string operations - String type conversion - Trim string

Summary

This guide has demonstrated the most commonly used string operations, such as string concatenation and type conversions to int, float, list, and datetime. You have learned substrings lookup, replace, split, and trim operations and how to get string length, reverse string, and replace substring from a given string.

Andrei Maksimov

I’m a passionate Cloud Infrastructure Architect with more than 20 years of experience in IT. In addition to the tech, I'm covering Personal Finance topics at https://amaksimov.com.

Any of my posts represent my personal experience and opinion about the topic.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related Posts

Maximize Your Business with AWS Startup Credits
Boto3 DynamoDB Update Item – Comprehensive Guide
Mastering AWS EC2 Instances – Comprehensive Guide
Boto3 DynamoDB create_backup – Easy DynamoDB Backups

Subscribe now to get the latest updates!

>