Как удалить элемент из строки python
Перейти к содержимому

Как удалить элемент из строки python

  • автор:

How To Remove Characters from a String in Python

How To Remove Characters from a String in Python

This article describes two common methods that you can use to remove characters from a string using Python:

  • the String replace() method
  • the String translate() method

To learn some different ways to remove spaces from a string in Python, refer to Remove Spaces from a String in Python.

A Python String object is immutable, so you can’t change its value. Any method that manipulates a string value returns a new String object.

The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove characters.

Remove Characters From a String Using the replace() Method

The String replace() method replaces a character with a new character. You can remove a character from a string by providing the character(s) to replace as the first argument and an empty string as the second argument.

Declare the string variable:

Replace the character with an empty string:

The output shows that both occurrences of the character a were removed from the string.

Remove Newline Characters From a String Using the replace() Method

Declare a string variable with some newline characters:

Replace the newline character with an empty string:

The output shows that both newline characters ( \n ) were removed from the string.

Remove a Substring from a String Using the replace() Method

The replace() method takes strings as arguments, so you can also replace a word in string.

Declare the string variable:

Replace a word with an empty string:

The output shows that the string Hello was removed from the input string.

Remove Characters a Specific Number of Times Using the replace() Method

You can pass a third argument in the replace() method to specify the number of replacements to perform in the string before stopping. For example, if you specify 2 as the third argument, then only the first 2 occurrences of the given characters are replaced.

Declare the string variable:

Replace the first two occurrences of the character with the new character:

The output shows that the first two occurrences of the a character were replaced by the A character. Since the replacement was done only twice, the other occurrences of a remain in the string.

Remove Characters From a String Using the translate() Method

The Python string translate() method replaces each character in the string using the given mapping table or dictionary.

Declare a string variable:

Get the Unicode code point value of a character and replace it with None :

The output shows that both occurrences of the b character were removed from the string as defined in the custom dictionary.

Remove Multiple Characters From a String using the translate() method

You can replace multiple characters in a string using the translate() method. The following example uses a custom dictionary, , that replaces all occurrences of a , b , and c in the given string with None .

Declare the string variable:

Replace all the characters abc with None :

The output shows that all occurrences of a , b , and c were removed from the string as defined in the custom dictionary.

Remove Newline Characters From a String Using the translate() Method

You can replace newline characters in a string using the translate() method. The following example uses a custom dictionary, , that replaces all occurrences of \n in the given string with None .

Declare the string variable:

Replace all the \n characters with None :

The output shows that all occurrences of the newline character \n were removed from the string as defined in the custom dictionary.

Conclusion

In this tutorial, you learned some of the methods you can use to remove characters from strings in Python. Continue your learning about Python strings.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Python Remove Character from a String – How to Delete Characters from Strings

Python Remove Character from a String – How to Delete Characters from Strings

In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result.

It is important to remember that the original string will not be altered because strings are immutable.

In this article, I will show you how to work with the replace() and translate() methods through the use of code examples.

How to use Python’s replace() method

Here is the basic syntax for the replace() method.

The old_str parameter represents the substring you want to replace.

The new_str parameter represents the new substring you want to use.

The optional_max parameter represents the maximum count of times to replace the old substring with the new substring.

The return value for the replace() method will be a copy of the original string with the old substring replaced with the new substring.

Python replace() example

Let’s take a look at some examples.

In this first example, we have a string called developer with my name assigned to it.

If we wanted to remove my last name, we can use the replace() method like this:

This tells the computer to take the old substring of Wilkins and replace it with an empty string.

If we print out the result then this is what we would get:

Screen-Shot-2022-03-06-at-8.41.55-PM

It is important to remember that the original string remains unchanged because strings are immutable. The replace() method will return a new string.

In this next example, we want to use the optional_max parameter to set the number of times we want to remove the letter s from my name.

This line of code says to remove the letter s only twice from the string Jessica Wilkins .

If we were to print out the result, this is what it would look like:

Screen-Shot-2022-03-06-at-8.55.22-PM

How to use Python’s translate() method

Another way to remove characters from a string is to use the translate() method. This method returns a new string where each character from the old string is mapped to a character from the translation table and translated into a new string.

Here is the basic syntax for Python’s translate() method.

Python translate() example

Let’s take a look at some examples to better understand the translate() method.

In this example, we want to remove all instances of the letter i from the string Jessica Wilkins .

We first need to use Python’s built in ord() function to get the Unicode code point value for the letter i . The ord() function will return a numerical value.

For our table, we need to assign the value of None so the computer will know to replace the letter i with nothing.

Now we use our table inside the translate() method.

If we were to print out the result, this is what it would look like:

Screen-Shot-2022-03-06-at-10.24.52-PM

In this next example, we want to return a new string with the letters e , s , and i removed. To do this, we can use an iterator in our table parameter.

That line of code tells the computer to find all occurrences of e , s , and i and replace it with None .

If we were to print out the result, this is what it would look like:

Screen-Shot-2022-03-06-at-10.37.10-PM

Conclusion

In Python you can use the replace() and translate() methods to specify which characters you want to remove from the string and return a new modified string result.

It is important to remember that the original string will not be altered because strings are immutable.

Here is the basic syntax for the replace() method.

The return value for the replace() method will be a copy of the original string with the old substring replaced with the new substring.

Another way to remove characters from a string is to use the translate() method. This method returns a new string where each character from the old string is mapped to a character from the translation table and translated into a new string.

Как удалить символ из строки в Python

Иногда мы хотим удалить все вхождения символа из строки. Есть два распространенных способа добиться этого:

  1. Использование функции String replace().
  2. Использование функции string translate().

Как удалить символ из строки с помощью replace()?

Мы можем использовать строковую функцию replace() для замены символа новым символом. Если мы предоставим пустую строку в качестве второго аргумента, то символ будет удален из строки.

Обратите внимание, что строка неизменна в Python, поэтому эта функция вернет новую строку, а исходная строка останется неизменной.

С помощью translate()

Строковая функция translate() заменяет каждый символ в строке, используя заданную таблицу перевода. Мы должны указать кодовую точку Unicode для символа и «None» в качестве замены, чтобы удалить его из строки результата. Мы можем использовать функцию ord(), чтобы получить кодовую точку Unicode символа.

Если вы хотите заменить несколько символов, это легко сделать с помощью итератора. Давайте посмотрим, как удалить символы «a», «b» и «c» из строки.

Удаление пробелов из строки

Удаление новой строки

Как удалить слово из строки?

Аргументами функции replace() является строка. Давайте посмотрим, как удалить слово из строки.

Как удалить указанное количество раз?

Мы также можем передать третий параметр в функцию replace(), чтобы указать, сколько раз должна выполняться замена.

5 Ways to Remove a Character from String in Python

The following methods are used to remove a specific character from a string in Python.

  1. By using Naive method
  2. By using replace() function
  3. By using slice and concatenation
  4. By using join() and list comprehension
  5. By using translate() method

Note that the string is immutable in Python. So the original string remains unchanged and a new string is returned by these methods.

1. Removing a Character from String using the Naive method

In this method, we have to run a loop and append the characters and build a new string from the existing characters except when the index is n. (where n is the index of the character to be removed)

Output:

Original string: DivasDwivedi
String after removal of i’th character : DivsDwivedi

2. Removal of Character from a String using replace() Method

Output:

Original string: Engineering
The string after removal of character: Enginring
The string after removal of character: Enginering

3. Removal of Character from a String using Slicing and Concatenation

Output:

Original string: Engineering
String after removal of character: Enineering

4. Removal of Character from a String using join() method and list comprehension

In this technique, every element of the string is converted to an equivalent element of a list, after which each of them is joined to form a string excluding the particular character to be removed.

Output:

Original string: Engineering
String after removal of character: Enineering

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *