DEV Community

Cover image for Python : String Manipulations
Eric The Coder
Eric The Coder

Posted on

Python : String Manipulations

The Python crash course is free and will be posted here on dev.to. I will publish a new article every two days or so. To not miss anything, you can follow me on twitter: Follow @EricTheCoder_

String Manipulations

Let's now see in a little more detail how to create and manipulate character strings (Strings) with Python.

A variable of type String can be created with single or double quotes

name = 'Mike'

# or

name = "Mike"

Enter fullscreen mode Exit fullscreen mode

Python allows you to insert special characters into your Strings.

message = "Hello \nWorld"
print(message)
# Hello
# World
Enter fullscreen mode Exit fullscreen mode

The special character “\n” will be replaced by a line break. Python provides you with several special characters. Here is a list: https://www.w3schools.com/python/gloss_python_escape_characters.asp

Interpolation

Using the “f” prefix displays the contents of the variable specified between the brackets {}

name = "Mike"

print(f"Hello {name}")
# Hello Mike
Enter fullscreen mode Exit fullscreen mode

Python can also execute any expression inside the {} brackets, so this concept can become very powerful. Here is an example:

name = "Mike"

print(f"Hello {name.upper()}")
# Hello MIKE
Enter fullscreen mode Exit fullscreen mode

It is also possible to join two Strings with the "+" (plus) operator

name = "Mike"

print("Hello " + name)
# Hello Mike
Enter fullscreen mode Exit fullscreen mode

Ignore special characters

Using the “r” prefix displays the contents of the String as is. That is to say without taking into account special characters (ex. \n)

message = r"https:\\example.com\index.html"
print(message)
# https:\\example.com\index.html
Enter fullscreen mode Exit fullscreen mode

Here the use of the “r” prefix allows the path to be displayed correctly. Otherwise Python would have interpreted the double backslash "\\" as a special character.

String over multiple lines

Python also allows you to create a String exactly as entered even with line breaks. To do this you must use three quotes.

message = """This is multiline
String that is easier to
read and assign"""

print(message)
# This is multiline
# String that is easier to
# read and assign
Enter fullscreen mode Exit fullscreen mode

As a result, reading the String in the code is very explicit.

Retrieving part of String

Python allows to retrieve only part of the String.

A String variable is indeed composed of several characters that can be read one by one or in groups. Here is some example

product = "iPhone 12"
# position 012345678

print(product[0]) 
# i

print(product[2]) 
# h

print(product[1:6])
# Phone
Enter fullscreen mode Exit fullscreen mode

Each character is associated with a position number. The first position is always 0. To access a particular position, it must be specified between square brackets []

Note that it is not possible to modify the String in this way. Any attempt to modify will return an error.

product = "iPhone 12"
product[0] = "e"

# TypeError: 'str' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

It is possible to access the characters of the String from the end.

message = "Hello World";

print(message[-1])
# d
Enter fullscreen mode Exit fullscreen mode

Position -1 represents the last character, -2 the penultimate, and so on.

When retrieving several characters, if one of the two positions is omitted, the retrieval will be from the beginning of the String

message = "Hello World";

print(message[:5])
# Hello

print(message[-5:])
# World
Enter fullscreen mode Exit fullscreen mode

String Manipulations

Python has several functions that allow you to transform the contents of the String. Here are a few :

Uppercase and lowercase conversion

name = 'Mike Taylor'

print(name.lower())
# mike taylor

print(name.upper())
# MIKE TAYLOR

Enter fullscreen mode Exit fullscreen mode

Remove white spaces before and after a String

message = "  Hello World        "

print(message.strip())
# "Hello World"

Enter fullscreen mode Exit fullscreen mode

Return the number of characters in the String

name = "Mike Taylor"

nb_char = len(name)

print(nb_char)
# 11
Enter fullscreen mode Exit fullscreen mode

Change the first letter of a String to uppercase

name = "mike"

name_cap = name.capitalize() 

print(name_cap)
# Mike
Enter fullscreen mode Exit fullscreen mode

Change the first letter of all words in a String to uppercase

name = 'mike Taylor'

name_title = name.title() 

print(name_title)
# Mike Taylor
Enter fullscreen mode Exit fullscreen mode

Check if the String starts or ends with a particular character or characters

name = 'Mike'

print(name.startswith('M')) 
# True

print(name.endswith('ke')) 
# True
Enter fullscreen mode Exit fullscreen mode

Replace part of the String with other characters

name = "Mike"

new_name = name.replace('M', 'P')

print(new_name)
# Pike
Enter fullscreen mode Exit fullscreen mode

Return the position of a specific character

name = "Mike"

print(name.find('k'))
# 2
Enter fullscreen mode Exit fullscreen mode

Note that the first position always starts at zero and if the character is not found, the function will return -1

Conclusion

That's all for today, I'll post a new article every other day or so. To make sure you don't miss anything, you can follow me on twitter: Follow @ EricTheCoder_

Top comments (0)