Working with strings in Python

Andrei Maksimov

Andrei Maksimov

0
(0)

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 to that, it is probably the number one choice if you’re busy with cloud automation tasks. This article illustrates the use of 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 operations 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 to mention, 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’ve 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 split() function that can be used to split sentence 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 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 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

There are several methods in Python, which you can use to lookup 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 find() built-in function that returns the index of the first instance of a substring in a string. If the desired substring 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 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, type conversions to int, float, list, and datetime. You have learned substrings lookup, replace, split, trim operations, and how to get string length, reverse string, replace substring from a given string.

How useful was this post?

Click on a star to rate it!

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Top rated Udemy Courses to improve you career

Subscribe to our updates

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to be an author of another post?

We’re looking for skilled technical authors for our blog!

Leave a comment

If you’d like to ask a question about the code or piece of configuration, feel free to use https://codeshare.io/ or a similar tool as Facebook comments are breaking code formatting.