This content originally appeared on DEV Community and was authored by Eric The Coder
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"
Python allows you to insert special characters into your Strings.
message = "Hello \nWorld"
print(message)
# Hello
# World
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
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
It is also possible to join two Strings with the "+" (plus) operator
name = "Mike"
print("Hello " + name)
# Hello Mike
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
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
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
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
It is possible to access the characters of the String from the end.
message = "Hello World";
print(message[-1])
# d
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
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
Remove white spaces before and after a String
message = " Hello World "
print(message.strip())
# "Hello World"
Return the number of characters in the String
name = "Mike Taylor"
nb_char = len(name)
print(nb_char)
# 11
Change the first letter of a String to uppercase
name = "mike"
name_cap = name.capitalize()
print(name_cap)
# Mike
Change the first letter of all words in a String to uppercase
name = 'mike Taylor'
name_title = name.title()
print(name_title)
# Mike Taylor
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
Replace part of the String with other characters
name = "Mike"
new_name = name.replace('M', 'P')
print(new_name)
# Pike
Return the position of a specific character
name = "Mike"
print(name.find('k'))
# 2
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_
This content originally appeared on DEV Community and was authored by Eric The Coder
Eric The Coder | Sciencx (2022-04-23T14:48:26+00:00) Python : String Manipulations. Retrieved from https://www.scien.cx/2022/04/23/python-string-manipulations/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.