Sign In
Sign In

Data Types in Python

Data Types in Python
Hostman Team
Technical writer
Python
06.12.2023
Reading time: 7 min

Python is a fully object-oriented programming language. Hence, all data in it is objects, which can be embedded at the language level or declared manually. 

Objects are instances of a class and the basic building blocks of any program, which are allocated memory to store data in them. So, for example, when we write x = 5 in code, we create an instance of the int class with the value 5 and assign it to the variable x. Now x is an object of the int type.

All objects have unique data types (int, string, list, etc.) and are created using the constructors of their respective classes. Classes, in turn, are mechanisms that define the behavior of objects thanks to unique attributes and methods. 

In this article, we will look at what data types there are in Python and talk about the features of each of them.

Variables

Variables in Python are named memory locations that store a variety of values within a Python program.

Each variable has its own data type, which tells the interpreter what can be stored in the variable and how much memory should be allocated for it.

The declaration of a variable is as follows:

x = 10

First of all, we specify the name of the variable, then we put an equal sign, and after that, we pass the value that will be assigned to the specified variable.

Each variable has its own location in memory. You can determine it using the id() function:

x = 10
print(id(x))

For the variable x from the example above, the location will be like this:

168d493b 3b23 4359 9edc 902cb8ba881a

There is also a type() function in Python, that allows us to find out the data type selected for a particular variable:

x = 10
print(type(x))

As you can see from the image below, an integer data type has been defined for x.

Ec3965d6 B426 48ba B32a E06d6bad2d82

The process of declaring a data type is called typing. It can be static or dynamic. Python uses the latter. That's why when the same variable is used, it can represent objects of completely different data types. For example:

first_example = 'Hello'
print(type(first_example))

first_example = 100
print(type(first_example))

first_example = 3.14
print(type(first_example))

In all cases of calling print, we will see a different result. 

Built-in data types

In this section, we will look at all the basic data types in the Python programming language. They can be divided into two groups: immutable and mutable objects.

You cannot change (mutate) the data in the immutable objects. You can only create a new object with the specified value and the same name. Immutable objects are objects of the numeric, string or tuple type.

Mutable objects, in turn, can be changed. This group includes objects of the list, dictionary or set types.

To check if the object is mutable, let's use the id() function and compare the memory locations before and after changes were made:

first_example = 50
second_example = [50, 100, 150]
print(f'Memory location before changing int object = {first_example} : {id(first_example)}')
print(f'Memory location before changing list object = {second_example} : {id(second_example)}')
first_example += 50
second_example += [200]
print(f'Memory location after changing int object = {first_example} : {id(first_example)}'')
print(f'Memory location after changing list object = {second_example} : {id(second_example)}')

You can see that when performing the addition operation with a variable of int type, a new object is created, the name of which is saved, but the value of the memory location is not. When adding a new value to an object of the list type, the address in memory does not change, which confirms its mutability.

You should take into account the mutability when working with functions. When you call a function with a mutable object as an argument, the function may perform mutations on that object, which will affect the original object. It is generally better to avoid mutating arguments inside your functions.

Numeric and boolean

First of all, let's look at the numeric data type in Python. 

Below is a table containing the name and description of the numeric data type, along with its notation and examples. We also added the boolean data type here.

Data type

Description

Example

Whole numbers (int)

Positive and negative numbers without decimals.

example1 = 5

example2 = -1234

Floating point numbers (float)

Positive and negative numbers with decimals

example3 = 3.14

example4 = -43.4132

Complex numbers (complex)

Numbers in the format: a + bj

where a and b are real numbers and j is an imaginary unit.

Complex numbers are passed using the complex() function.

The syntax for displaying the real part:

variable_name.real

The syntax for displaying the imaginary part:

variable_name.imag

example5 = complex(5,4)

Boolean (bool)

The boolean data type takes only 2 values: True and False

It is often used to implement branching or checkboxes.

example7 = True

example8 = False

Strings

The string data type stores text information or a sequence of bytes. To declare a string, you need to use single, double or triple quotes, as shown in the example below:

example_srt1 = ‘Example string #1’
example_srt2 = “Example string #2”
example_srt3 = '''Example string #3'''

As we said before, strings are immutable objects.

Lists

List in Python is an ordered collection of items. These items can be of different data types. Lists are mutable, meaning you can add, remove, and modify elements in a list.

You can create a list by using square brackets with elements between them, separated by commas, as shown in the example below:

example_list = [1, 5.7, 'hello']

To retrieve elements from a list, use indices. You can retrieve a single element or a slice. Example:

example_list = [1, 5.7, 'hello']
print(f'Third element of the list: {example_list[2]}')
print(f'First and second element of the list: {example_list[0:2]}')

Tuples

Tuples in Python are similar to lists but immutable. Their advantage is that the interpreter works with them much faster. So, if you want your program to run faster and your data to remain immutable, use tuples.

To create a tuple, we need to put comma-separated elements inside parentheses, as shown in the example below:

example_tuple = (1, 5.7, 'hello')

As to retrieving elements, we can do it using indices, just like lists. Just remember that you cannot mutate them.

Dictionaries

Dictionaries are an unordered list of key-value pairs. They provide quick access to data by using the appropriate key.

To declare a dictionary, list the data in a key-value format in curly braces, as shown in the example below:

example_dict = {
    'name':'Peter',
    'age':33,
    'country':'Netherlands'
}

It's important to remember that values can be of any data type, and keys are only immutable.

To get a value, use the corresponding key:

example_dict = {
    'name':'Peter',
    'age':33,
    'country':'Netherlands'
}

print(f'Peter is from: {example_dict["country"]}')
print(f'His age is: {example_dict["age"]}')

Sets

A set is a collection of unique immutable elements.

To declare a set, you must list the elements separated by commas in curly braces, as shown in the example below:

example_set = {1,2,3,4,5}

If we try to pass duplicate elements into a set, the interpreter will automatically remove them. 

example_set = {1,2,3,4,5,1,2,3,4,5}
print(example_set)

As a result, the print(example_set) function will print the following:

F7c75f0d 64a6 4547 8034 23aa9f277a5d

Another feature of sets is that we can perform a number of mathematical operations (union, difference, intersection) on them.

What to remember

  • All objects have their own unique data types (int, string, list, etc.) and are created using the constructors of the corresponding classes.

  • Variables in Python are named memory locations that store values. Each variable has its own data type, which tells the interpreter what can be stored in that variable and how much memory should be allocated to it.

  • You cannot change the state and contents of immutable objects. Instead, you can create a new object with the specified value and the same name. Immutable objects are of the number, string or tuple types.

  • Mutable objects can be changed. This group includes the list, dictionary, and set types.

  • The numeric data type includes integers, floating point numbers, and complex numbers.

  • The boolean data type takes only two values: True or False.

  • The string data type stores text information or a sequence of bytes.

  • Lists are ordered collections of items that can be of different data types.

  • Tuples in Python are the same as lists, but immutable.

  • A dictionary is an unordered list of key-value pairs.

  • A set is a collection of unique and unordered elements of an immutable type.

Python
06.12.2023
Reading time: 7 min

Similar

Python

How to Install and Set Up PyTorch

PyTorch is a free, open-source deep learning library. With its help, a computer can detect objects, classify images, generate text, and perform other complex tasks. PyTorch is also a rich tool ecosystem that supports and accelerates AI development and research. In this article, we will cover only the basics: we will learn how to install PyTorch and verify that it works. To work with PyTorch, you will need: At least 1 GB of RAM. Installed Python 3 and pip.  A configured local development environment. Deep knowledge of machine learning is not required for this tutorial. It is assumed that you are familiar with basic Python terms and concepts. Installing PyTorch We will be working in a Windows environment but using the command line. This makes the tutorial almost universal—you can use the same commands on Linux and macOS. First, create a workspace where you will work with Torch Python. Navigate to the directory where you want to place the new folder and create it: mkdir pytorch Inside the pytorch directory, create a new virtual environment. This is necessary to isolate projects and, if needed, use different library versions. python3 -m venv virtualpytorch To activate the virtual environment, first go to the newly created directory: cd virtualpytorch Inside, there is a scripts folder (on Windows) or bin (on other OS). Navigate to it: cd scripts Activate the virtual environment using a bat file by running the following command in the terminal: activate.bat The workspace is now ready. The next step is to install the PyTorch library. The easiest way to find the installation command is to check the official website. There is a convenient form where you select the required parameters. As an example, install the stable version for Windows using CPU via pip. Select these parameters in the form, and you will get the necessary command: pip3 install torch torchvision torchaudio Copy and execute the pip install torch command in the Windows command line. You are also installing two sub-libraries: torchvision – contains popular datasets, model architectures, and image transformations for computer vision. torchaudio – a library for processing audio and signals using PyTorch, providing input/output functions, signal processing, datasets, model implementations, and application components. This is the standard setup often used when first exploring the library. The method described above is not the only way to install PyTorch. If Anaconda is installed on Windows, you can use its graphical interface. If your computer has NVIDIA GPUs, you can select the CUDA version instead of CPU. In that case, the installation command will be different. All possible local installation methods are listed in the official documentation. You can also find commands for installing older versions of the library there. To install them, just select the required version and install it the same way as the current package builds. You don't need to write a script to check if the library is working. The Python interpreter has enough capabilities to perform basic operations. If you have successfully installed PyTorch in the previous steps, then launching the Python interpreter won’t be an issue. Run the following command in the command line: python Then enter the following code: import torch x = torch.rand(5, 3) print(x) You should see an output similar to this: tensor([[0.0925, 0.3696, 0.4949], [0.0240, 0.2642, 0.1545], [0.7274, 0.4975, 0.0753], [0.4438, 0.9685, 0.5022], [0.4757, 0.6715, 0.4298]]) Now, you can move on to solving more complex tasks. PyTorch Usage Example To make learning basic concepts more engaging, let’s do it in practice. For example, let’s create a neural network using PyTorch that can recognize the digit shown in an image. Prerequisites To create a neural network, we need to import eight modules: import torch import torchvision import torch.nn.functional as F import matplotlib.pyplot as plt import torch.nn as nn import torch.optim as optim from torchvision import transforms, datasets All of these are standard PyTorch libraries plus Matplotlib. They handle image processing, optimization, neural network construction, and graph visualization. Loading and Transforming Data We will train the neural network on the MNIST dataset, which contains 70,000 images of handwritten digits. 60,000 images will be used for training. 10,000 images will be used for testing. Each image is 28 × 28 pixels. Each image has a label representing the digit (e.g., 1, 2, 5, etc.). train = datasets.MNIST("", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) test = datasets.MNIST("", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) trainset = torch.utils.data.DataLoader(train, batch_size=15, shuffle=True) testset = torch.utils.data.DataLoader(test, batch_size=15, shuffle=True) First, we divide the data into training and testing sets by setting train=True/False. The test set must contain data that the machine has not seen before. Otherwise, the neural network’s performance would be biased. Setting shuffle=True helps reduce bias and overfitting. Imagine that the dataset contains many consecutive "1"s. If the machine gets too good at recognizing only the digit 1, it might struggle to recognize other numbers. Shuffling the data prevents the model from overfitting specific patterns and ensures a more generalized learning process. Definition and Initialization of the Neural Network The next step is defining the neural network: class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 86) self.fc2 = nn.Linear(86, 86) self.fc3 = nn.Linear(86, 86) self.fc4 = nn.Linear(86, 10) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = self.fc4(x) return F.log_softmax(x, dim=1) model = NeuralNetwork() The neural network consists of four layers: one input layer, two hidden layers, and one output layer. The Linear type represents a simple neural network. For each layer, it is necessary to specify the number of inputs and outputs. The output number of one layer becomes the input for the next layer. The input layer has 784 nodes. This is the result of multiplying 28 × 28 (the image size in pixels). The first hidden layer has 86 output nodes, so the input to the next layer must be 86 as well.The same logic applies further. 86 is an arbitrary number—you can use a different value. The output layer contains 10 nodes because the images represent digits from 0 to 9. Each time data passes through a layer, it is processed by an activation function. There are several activation functions. In this example, we use ReLU (Rectified Linear Unit). This function returns 0 if the value is negative or the value itself if it is positive. The softmax function is used at the output layer to normalize values. For example, it might return an 80% probability that the digit in the image is 1, or a 30% probability that the digit is 5, and so on. The highest probability is selected as the final prediction. Training The next step is training. optimizer = optim.Adam(model.parameters(), lr=0.001) EPOCHS = 3 for epoch in range(EPOCHS): for data in trainset: X, y = data model.zero_grad() output = model(X.view(-1, 28 * 28)) loss = F.nll_loss(output, y) loss.backward() optimizer.step() print(loss) The optimizer calculates the difference (loss) between the actual data and the prediction, adjusts the weights, recalculates the loss, and continues the cycle until the loss is minimized. Training Verification Here, we compare the actual values with the predictions made by the model. For this tutorial, the accuracy is high because the neural network effectively recognizes each digit. correct = 0 total = 0 with torch.no_grad(): for data in testset: data_input, target = data output = model(data_input.view(-1, 784)) for idx, i in enumerate(output): if torch.argmax(i) == target[idx]: correct += 1 total += 1 print('Accuracy: %d %%' % (100 * correct / total)) To verify that the neural network works, pass it an image of a digit from the test set: plt.imshow(X[1].view(28,28)) plt.show() print(torch.argmax(model(X[1].view(-1, 784))[0])) The output should display the digit shown in the provided image. Final Script Here’s the full script you can run to see how the neural network works: import torch import torchvision import torch.nn.functional as F import matplotlib.pyplot as plt import torch.nn as nn import torch.optim as optim from torchvision import transforms, datasets train = datasets.MNIST("", train=True, download=True, transform = transforms.Compose([transforms.ToTensor()])) test = datasets.MNIST("", train=False, download=True, transform = transforms.Compose([transforms.ToTensor()])) trainset = torch.utils.data.DataLoader(train, batch_size=15, shuffle=True) testset = torch.utils.data.DataLoader(test, batch_size=15, shuffle=True) class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 86) self.fc2 = nn.Linear(86, 86) self.fc3 = nn.Linear(86, 86) self.fc4 = nn.Linear(86, 10) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = self.fc4(x) return F.log_softmax(x, dim=1) model = NeuralNetwork() optimizer = optim.Adam(model.parameters(), lr=0.001) EPOCHS = 3 for epoch in range(EPOCHS): for data in trainset: X, y = data model.zero_grad() output = model(X.view(-1, 28 * 28)) loss = F.nll_loss(output, y) loss.backward() optimizer.step() print(loss) correct = 0 total = 0 with torch.no_grad(): for data in testset: data_input, target = data output = model(data_input.view(-1, 784)) for idx, i in enumerate(output): if torch.argmax(i) == target[idx]: correct += 1 total += 1 print('Accuracy: %d %%' % (100 * correct / total)) plt.imshow(X[1].view(28,28)) plt.show() print(torch.argmax(model(X[1].view(-1, 784))[0])) Each time we run the network, it will take a random image from the test set and analyze the digit depicted on it. After the process is completed, it will display the recognition accuracy in percentage, the image itself, and the digit recognized by the neural network. This is how it looks: Conclusion PyTorch is a powerful open-source machine learning platform that accelerates the transition from research prototypes to production deployments. With it, you can solve various tasks in the fields of artificial intelligence and neural networks. You don’t need deep knowledge of machine learning to begin working with PyTorch. It is enough to know the basic concepts to repeat and even modify popular procedures like image recognition to suit your needs. A big advantage of PyTorch is the large user community that writes tutorials and shares examples of using the library. Object recognition in images is one of the simplest and most popular tasks in PyTorch for beginners. However, the capabilities of the library are not limited to this. To create powerful neural networks, you need a lot of training data. These can be stored, for example, in an object-based S3 storage such as Hostman, with instant data access via API or web interface. This is an excellent solution for storing large volumes of information.
01 April 2025 · 10 min to read
Python

How to Create a Virtual Environment in Python

This article will teach you how to create a Python virtual environment. It is useful for Python developers to avoid issues with different versions of libraries. A simple example: You have two applications that rely on the same library, but each requires a different version. Another example: You want to ensure that your application runs independently of library updates installed in the global Python storage. A third example: You do not have access to this global storage. The solution in all three cases is to create a Python virtual environment.  The module name venv is short for Virtual Environment. It is a great tool for project isolation, functioning like a sandbox. It allows you to run an application with its dependencies without interfering with other applications that use different versions of the same software. As a result, each application runs in its own virtual environment, isolated from others, increasing the overall stability of all applications. How to Create a Virtual Environment in Python 3 Good news: You don’t need to install venv separately on Windows—it is part of the standard Python 3 library and comes with the interpreter. On Linux, however, venv is not always included in the OS package, so you might need to install it. On Ubuntu/Debian, use the following command: sudo apt install -y python3-venv Some Python packages require compilation from source code, so you might also need to install the following dependencies: sudo apt install -y build-essential libssl-dev libffi-dev python3-dev Now, let's see how to create a Python 3 virtual environment in Windows and Linux using venv. Step 1: Creating the Virtual Environment Use the following command for all operating systems: python -m venv venv Here, -m tells Python to run the venv module. The second venv specifies the directory (venv/lib/python3.8/site-packages/, the version may vary) where Python will store all libraries and components required for isolated application execution. Step 2: Activating the Virtual Environment Activation differs between Windows and Linux. On Windows, run: venv\Scripts\activate.bat On Linux (and MacOS), use: source venv/bin/activate If everything is set up correctly, you will see an output like this: (venv) root@purplegate:/var/test# Now you can start working on your project within the isolated environment! Other Tools Of course, venv is the most modern tool for creating virtual environments. However, it was only introduced in Python 3. So what should those working with older versions of Python do? The answer: try other tools that offer additional useful features—otherwise, we wouldn’t mention them at all. Below is a brief overview of these alternatives, followed by a more detailed look at the most popular one. virtualenv – A simple and user-friendly tool that is widely used when deploying applications. It’s useful to learn, and we’ll provide instructions on how to use it below. pyenv – Allows you to isolate different Python versions. This is helpful if you need to run multiple versions of Python, for example, for testing purposes. virtualenvwrapper – A wrapper for virtualenv that helps manage virtual environments by simplifying tasks like creating, copying, and deleting environments. One of its advantages is that it allows easy switching between environments and supports various plugins for extended functionality. Creating a Virtual Environment Using virtualenv Let's go through the process using Linux as an example. However, running Python virtualenv on Windows is almost the same, with differences mainly in file paths and scripts, which we’ll mention separately. Step 1: Install virtualenv You can download the source code and install it manually, but the easiest way is to use pip. Just enter the following command in your terminal: pip install virtualenv Step 2: Create a Virtual Environment This step requires just a simple command: virtualenv myenv This will create a new directory in the current folder. Instead of myenv, you can use any other name for your environment. Directory structure of the virtual environment: /myenv/bin – Contains scripts for managing the environment, a copy of the Python interpreter, pip, and some package management utilities. In Windows, this folder is located at /myenv/Scripts. /myenv/lib and /myenv/include – Store the environment’s core libraries. Any newly installed files will go into /myenv/lib/pythonX.X/site-packages/, where X.X represents your Python version. Step 3: Activate the Virtual Environment Activation differs slightly between Linux and Windows. For Linux, use: source myenv/bin/activate For Windows, run: myenv\Scripts\activate.bat Once activated, you will see the virtual environment’s name in your command line prompt. If you create the virtual environment with the --system-site-packages flag, it will have access to the system-wide package storage: virtualenv --system-site-packages myenv Keep in mind that the system package paths differ: Linux: /usr/lib/python3.8/site-packages Windows: \Python38\Lib\site-packages Version numbers may vary depending on your installation. Step 4: Deactivate the Virtual Environment Once you’re done working in the Python virtual environment, you should exit it properly. For Linux, run: deactivate For Windows, use the batch file: myenv\Scripts\deactivate.bat What's New? In addition to the venv and virtualenv modules we’ve already covered, there are more modern tools that provide greater flexibility in managing Python projects, including virtual environments: Poetry – A package manager that helps manage application dependencies within a virtual environment. It also simplifies testing and deployment by automating many processes. Pipenv – Another package manager that integrates pip and virtualenv, along with several other useful tools. It is designed to make environment and package management easier, as many developers eventually encounter version control issues in their projects. Each of these tools deserves a deep dive, but for now, let’s focus on the key features of both. Poetry: The Essentials Poetry handles all aspects of managing libraries within a virtual environment, including installing, updating, and publishing them. The functionality of pip alone is often insufficient for these tasks. Additionally, Poetry allows you to create and package applications with a single command (replace myproject with your actual project name): poetry new myproject If you want to initialize an existing directory as a Poetry project, use: poetry init Poetry can also: Publish projects to private repositories Track and manage dependencies Enforce version control Simplify working on private virtual servers by ensuring reliable project isolation Pipenv: The Essentials In simple terms, Pipenv is like pip + virtualenv, but with enhanced features. It eliminates the need for the traditional and sometimes cumbersome requirements.txt file. Instead, Pipenv uses: Pipfile.lock – Ensures package version consistency, which enhances security. Pipfile – A more advanced replacement for requirements.txt. Unlike its predecessor, Pipfile updates automatically as package versions change, which is particularly useful for teams, reducing dependency conflicts. Now you have a complete set of tools at your disposal, and managing multiple dependencies with different versions should no longer be a challenge! 
21 March 2025 · 6 min to read
Python

How to Delete Characters from a String in Python

When writing Python code, developers often need to modify string data. Common string modifications include: Removing specific characters from a sequence Replacing characters with others Changing letter case Joining substrings into a single sequence In this guide, we will focus on the first transformation—deleting characters from a string in Python. It’s important to note that strings in Python are immutable, meaning that any method or function that modifies a string will return a new string object with the changes applied. Methods for Deleting Characters from a String This section covers the main methods in Python used for deleting characters from a string. We will explore the following methods: replace() translate() re.sub() For each method, we will explain the syntax and provide practical examples. replace() The first Pyhton method we will discuss is replace(). It is used to replace specific characters in a string with others. Since strings are immutable, replace() returns a new string object with the modifications applied. Syntax: original_string.replace(old, new[, count]) Where: original_string – The string where modifications will take place old – The substring to be replaced new – The substring that will replace old count (optional) – The number of occurrences to replace (if omitted, all occurrences will be replaced) First, let’s remove all spaces from the string "H o s t m a n": example_str = "H o s t m a n" result_str = example_str.replace(" ", "") print(result_str) Output: Hostman We can also use the replace() method to remove newline characters (\n). example_str = "\nHostman\nVPS" print(f'Original string: {example_str}') result_str = example_str.replace("\n", " ") print(f'String after adjustments: {result_str}') Output: Original string: Hostman VPS String after adjustments: Hostman VPS The replace() method has an optional third argument, which specifies the number of replacements to perform. example_str = "Hostman VPS Hostman VPS Hostman VPS" print(f'Original string: {example_str}') result_str = example_str.replace("Hostman VPS", "", 2) print(f'String after adjustments: {result_str}') Output: Original string: Hostman VPS Hostman VPS Hostman VPS String after adjustments: Hostman VPS Here, only two occurrences of "Hostman VPS" were removed, while the third occurrence remained unchanged. We have now explored the replace() method and demonstrated its usage in different situations. Next, let’s see how we can delete and modify characters in a string using translate(). translate( The Python translate() method functions similarly to replace() but with additional flexibility. Instead of replacing characters one at a time, it allows mapping multiple characters using a dictionary or translation table. The method returns a new string object with the modifications applied. Syntax: original_string.translate(mapping_table) In the first example, let’s remove all occurrences of the $ symbol in a string and replace them with spaces: example_str = "Hostman$Cloud$—$Cloud$Service$Provider." print(f'Original string: {example_str}') result_str = example_str.translate({ord('$'): ' '}) print(f'String after adjustments: {result_str}') Output: Original string: Hostman$Cloud$—$Cloud$Service$Provider. String after adjustments: Hostman Cloud — Cloud Service Provider. To improve code readability, we can define the mapping table before calling translate(). This is useful when dealing with multiple replacements: example_str = "\nHostman%Cloud$—$Cloud$Service$Provider.\n" print(f'Original string: {example_str}') # Define translation table example_table = {ord('\n'): None, ord('$'): ' ', ord('%'): ' '} result_str = example_str.translate(example_table) print(f'String after adjustments: {result_str}') Output: Original string: Hostman%Cloud$—$Cloud$Service$Provider. String after adjustments: Hostman Cloud — Cloud Service Provider. re.sub() In addition to replace() and translate(), we can use regular expressions for more advanced character removal and replacement. Python's built-in re module provides the sub() method, which searches for a pattern in a string and replaces it. Syntax: re.sub(pattern, replacement, original_string [, count=0, flags=0]) pattern – The regular expression pattern to match replacement – The string or character that will replace the matched pattern original_string – The string where modifications will take place count (optional) – Limits the number of replacements (default is 0, meaning replace all occurrences) flags (optional) – Used to modify the behavior of the regex search Let's remove all whitespace characters (\s) using the sub() method from the re module: import re example_str = "H o s t m a n" print(f'Original string: {example_str}') result_str = re.sub('\s', '', example_str) print(f'String after adjustments: {result_str}') Output: Original string: H o s t m a nString after adjustments: Hostman Using Slices to Remove Characters In addition to using various methods to delete characters, Python also allows the use of slices. As we know, slices extract a sequence of characters from a string. To delete characters from a string by index in Python, we can use the following slice: example_str = "\nHostman \nVPS" print(f'Original string: {example_str}') result_str = example_str[1:9] + example_str[10:] print(f'String after adjustments: {result_str}') In this example, we used slices to remove newline characters. The output of the code: Original string:HostmanVPSString after adjustments: Hostman VPS Apart from using two slice parameters, you can also use a third one, which specifies the step size for index increments. For example, if we set the step to 2, it will remove every odd-indexed character in the string. Keep in mind that indexing starts at 0. Example: example_str = "Hostman Cloud" print(f'Original string: {example_str}') result_str = example_str[::2] print(f'String after adjustments: {result_str}') Output: Original string: Hostman CloudString after adjustments: HsmnCod Conclusion In this guide, we learned how to delete characters from a string in Python using different methods, including regular expressions and slices. The choice of method depends on the specific task. For example, the replace() method is suitable for simpler cases, while re.sub() is better for more complex situations.
21 March 2025 · 5 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support