Python str remove symbol

5 простых способов удалить символ из строки

Существует несколько методов, позволяющих удалить определенный символ из строки:

  • Примитивный метод.
  • Функция replace().
  • Срезы и конкатенация.
  • Метод join() и генератор списков.
  • Метод translate()

Важная деталь — строки в Python неизменяемы. Исходная строка останется нетронутой, а новую вернут методы, о которых написано выше.

Задачи по строкам и решения к ним у нас в телеграм канале PythonTurbo

1. Примитивный метод удаления символа из строки

Суть этого метода проста. Мы пишем цикл и создаем новую пустую строку. Цикл работает так: все символы кроме элемента с индексом n помещаются в новую строку. ( n — индекс элемента, который нам нужно удалить)

input_str = "pythonist" # Выводим в консоль исходную строку print ("Исходная строка: " + input_str) result_str = "" for i in range(0, len(input_str)): if i != 3: result_str = result_str + input_str[i] # Выводим в консоль строку после удаления i-го элемента print ("Строка после удаления i-го элемента: " + result_str)
Исходная строка: pythonist Строка после удаления i-го элемента: pytonist

2. Удаление элемента из строки с помощью метода replace()

str = "pythonist" print ("Исходная строка: " + str) res_str = str.replace('t', '') # Удаление всех 't' print("Строка после удаления всех символов t: " + res_str) # Удаление только первой t res_str = str.replace('t', '', 1) print ("Строка после удаления первого t: " + res_str)
Исходная строка: pythonist Строка после удаления всех символов t: pyhonis Строка после удаления первого t: pyhonist

Мини-задачка для вашей тренировки метода replace()

Читайте также:  Java response send file

«Напишите программу на Python для получения строки из заданной строки, в которой все вхождения первого символа заменены на ‘$’, кроме самого первого символа.»

Пример: print(change_char(‘restart’))
»»» resta$t

Решение задачки можно глянуть у нас в канале

3. Удаление символа с помощью срезов и конкатенации

str = "pythonist" print ("Исходная строка: " + str) # Удаляем элемент с индексом 3 # с помощью срезов и объединения res_str = str[:3] + str[4:] print ("Строка после удаления символа: " + res_str
Исходная строка: pythonist Строка после удаления символа: pytonist

4. Удаление символа с помощью метода join() и генераторов списков

Суть этого метода в том, чтобы конвертировать строку в эквивалентный список. После этого все элементы кроме того, который мы собираемся удалить, объединяются в строку.

str = "pythonist" print("Исходная строка: " + str) # Удаление элемента с индексом 2 # с помощью join() и генератора списков res_str = ''.join([str[i] for i in range(len(str)) if i != 2]) print("Строка после удаления символа: " + res_str)
Исходная строка: pythonist Строка после удаления символа: pyhonist

5. Удаление символа из строки с помощью метода translate()

str = 'pythonist123pythonist' print(str.translate())

Источник

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)

input_str = "DivasDwivedi" # Printing original string print ("Original string: " + input_str) result_str = "" for i in range(0, len(input_str)): if i != 3: result_str = result_str + input_str[i] # Printing string after removal print ("String after removal of i'th character : " + result_str)

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

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

str = "Engineering" print ("Original string: " + str) res_str = str.replace('e', '') # removes all occurrences of 'e' print ("The string after removal of character: " + res_str) # Removing 1st occurrence of e res_str = str.replace('e', '', 1) print ("The string after removal of character: " + res_str)

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

Читайте также:  Java regex match all but

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

str = "Engineering" print ("Original string: " + str) # Removing char at pos 3 # using slice + concatenation res_str = str[:2] + str[3:] print ("String after removal of character: " + res_str)

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.

str = "Engineering" print ("Original string: " + str) # Removing char at index 2 # using join() + list comprehension res_str = ''.join([str[i] for i in range(len(str)) if i != 2]) print ("String after removal of character: " + res_str)

Original string: Engineering
String after removal of character: Enineering

5. Removal of character from a string using translate() method

str = 'Engineer123Discipline' print(str.translate())

References

Источник

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:

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.

Читайте также:  Java program to translate language

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!

Источник

Оцените статью