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.
Table of contents
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)

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)

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)

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)

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)

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)

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)

You can use any delimiter in the split()
function, for example:
my_ip = "192.162.1.1"
octets = my_ip.split('.')
print(octets)

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)

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)

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")

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')

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")

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')

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)

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}'")

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.