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

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

  • автор:

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

Аватар пользователя Ivan Mamtsev

Удалить слово из строки можно с помощью функции sub из библиотеки для регулярных выражений re .

Рекомендуемые курсы

Похожие вопросы

  • python строки
  • python массивы
  • python строки
  • python массивы
  • python строки
  • файлы

ООО «Хекслет Рус» 432071, г. Ульяновск, пр-т Нариманова, дом 1Г, оф. 23 ОГРН 1217300010476

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

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

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

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

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

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

С помощью translate()

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

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

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

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

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

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

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

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

Remove Substring From String in Python

While handling text data in python, we sometimes need to remove a specific substring from the text. In this article, we will discuss different ways to remove a substring from a string in Python.

Remove Substring From String in Python Using split() Method

The split() method in Python is used to split a string into substrings at a separator. The split() method, when invoked on a string, takes a string in the form of a separator as its input argument. After execution, it returns a list of substrings from the original string, which is split at the separator.

To remove a substring from a string in Python using the split() method, we will use the following steps.

  • First, we will create an empty string named output_string to store the output string.
  • Then, we will use the split() method to split the string into substrings from the positions where we need to remove a specific substring. For this, we will invoke the split() method on the input string with the substring that needs to be removed as the input argument. After execution, the split() method will return a string of substrings. We will assign the list to a variable str_list .
  • Once we get the list of strings, we will iterate through the substrings in str_list using a for loop. During iteration, we will add the current substring to output_string using the string concatenation operation.

After execution of the for loop, we will get the required output string in the variable output_string . You can observe this in the following code.

In the output, you can observe that the substring python has been removed from the input string.

Remove Substring From String in Python Using Using the join() Method

Performing string concatenation several times requires unnecessary storage and time. Therefore, we can avoid that by using the join() method.

The join() method, when invoked on a separator string, takes an iterable object as its input argument. After execution, it returns a string consisting of the elements of the iterable object separated by the separator string.

To remove substring from a string in python using the join() method, we will use the following steps.

  • First, we will use the split() method to split the input string into substrings from the positions where we need to remove a specific substring. For this, we will invoke the split() method on the input string with the substring that needs to be removed as the input argument. After execution, the split() method will return a string of substrings. We will assign the list to a variable str_list .
  • Next, we will invoke the join() method on an empty string with str_list as its input argument.

After execution of the join() method, we will get the required string output as shown below.

Here, you can observe that we have converted the list returned by the split() method into a string using the join() method. Thus, we have avoided repeated string concatenation as we did in the previous example.

Remove Substring From String in Python Using the replace() Method

The replace() method is used to replace one or more characters from a string in python. When invoked on a string, the replace() method takes two substrings as its input argument. After execution, it replaces the substring in the first argument with that of the second input argument. Then it returns the modified string.

To remove a substring from a string using the replace() method, we will invoke the replace() method on the original string with the substring that is to be removed as the first input argument and an empty string as the second input argument.

After execution of the replace() method, we will get the output string as shown in the following example.

Here, we have removed the required substring from the input string in a single statement using the replace() method.

Remove Substring From String in PythonUsing Regular Expressions

Regular expressions provide us with efficient ways to manipulate strings in Python. We can also use regular expressions to remove a substring from a string in python. For this, we can use the re.split() method and the re.sub() method.

Remove Substring From String in Python Using re.split() Method

The re.split() method is used to split a text at a specified separator. The re.split() method takes a separator string as its first input argument and the text string as its second input argument. After execution, it returns a list of strings from the original string that are separated by the separator.

To remove a substring from a string in Python using the re.split() method, we will use the following steps.

  • First, we will create an empty string named output_string to store the output string.
  • Then, we will use the re.split() method to split the string into substrings from the positions where we need to remove a specific substring. For this, we will execute the re.split() method with the substring that needs to be removed as its first input argument and the text string as its second input argument. After execution, the re.split() method will return a string of substrings. We will assign the list to a variable str_list .
  • Once we get the list of strings, we will iterate through the substrings in str_list using a for loop. During iteration, we will add the current substring to output_string using the string concatenation operation.

After execution of the for loop, we will get the required output string in the variable output_string . You can observe this in the following code.

You can observe that the approach using the re.split() method is almost similar to the approach using the string split() method. However, both approaches have different execution speeds. If the input string is very large, the re.split() method should be the preferred choice to split the input string.

Performing string concatenation several times requires unnecessary memory and time. Therefore, we can avoid that by using the join() method.

To remove substring from a string in python using the join() method, we will use the following steps.

  • First, we will use the re.split() method to split the input string into substrings from the positions where we need to remove a specific substring.For this, we will execute the re.split() method with the substring that has to be removed as its first input argument and the text string as its second input argument. After execution, the re.split() method will return a string of substrings. We will assign the list to a variable str_list .
  • Next, we will invoke the join() method on an empty string with str_list as its input argument.

After execution of the join() method, we will get the required string output as shown below.

In this approach, we have obtained the output string in only two python statements. Also, we haven’t done repetitive string concatenation which takes unnecessary time.

Remove Substring From String in Python Using re.sub() Method

The re.sub() method is used to substitute one or more characters from a string in python. The re.sub() method takes three input arguments. The first input argument is the substring that needs to be substituted. The second input argument is the substitute substring. The original string is passed as the third input string.

After execution, the re.sub() method replaces the substring in the first argument with that of the second input argument. Then it returns the modified string.

To remove a substring from a string using the re.sub() method, we will execute the re.sub() method with the substring that is to be removed as the first input argument, an empty string as the second input argument, and the original string as the third input argument.

After execution of the re.sub() method, we will get the output string as shown in the following example.

The re.sub() method works in a similar manner to the replace() method. However, it is faster than the latter and should be the preferred choice.

Remove Substring From String in Python by Index

Sometimes, we might need to remove a substring from a string when we know its position in the string. To remove a substring from a string in python by index, we will use string slicing.

If we have to remove the substring from index i to j, we will make two slices of the string. The first slice will be from index 0 to i-1 and the second slice will be from index j+1 to the last character.

After obtaining the slices, we will concatenate the slices to obtain the output string as shown in the following example.

Conclusion

In this article, we have discussed different ways to remove a substring from a string in Python. Out of all the approaches, the approaches using re.sub() method and the replace() method have the best time complexity. Therefore, I would suggest you use these approaches in your program.

I hope you enjoyed reading this article. To learn more about python programming, you can read this article on how to remove all occurrences of a character in a list in Python. You might also like this article on how to check if a python string contains a number.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Python remove substring from a String + Examples

In this python tutorial, we will discuss Python remove substring from a string and also cover the below points:

  • Remove substring from string python regex
  • Remove substring from string python DataFrame
  • Python remove substring from string by index
  • Remove duplicate substring from string python
  • Remove the last substring from string python
  • Remove multiple substrings from string python
  • Remove the first substring from string python
  • Remove substring from beginning of string python
  • Python remove substring from a string if exists
  • Remove a substring from a string python pandas
  • How to remove all occurrences of a substring from a string in python
  • Python remove substring from the middle of a string

Table of Contents

Python remove substring from a String

A substring is a contiguous sequence of characters. We extract these substrings using the substring method.

  • When you give the substring method one number the result in the section from that position to the end of the string.
  • If you have two numbers, you get the section starting at the start index up to but not including the end position.
  • For example, abcdef is a string where the cd is a substring of this string.

Here is the syntax of Substring

Python remove substring from a String

  • In this section, we will learn how to remove substring from a string.
  • Python removes a character from a string offers multiple methods by which we can easily remove substring from a string.
    • String replace()

    String replace() method replaces a specified character with another specified character.

    Here is the Syntax of String replace()

    Let’s take an example to check how to remove substring from a string in Python.

    Here is the screenshot of following given code.

    Python remove substring from a string

    This is how to remove substring from a String in Python.

    Remove substring from string python regex

    • In this section, we will learn how to remove substring from string python regex.
    • Regular Expression is basically used for describing a search pattern so you can use regular expression for searching a specific string in a large amount of data.
    • You can verify that string has a proper format or not you can find a string and replace it with another string and you can even format the data into a proper form for importing so these are all uses of the regular expression.
    • Now over here I have shown you an example here.
    • There is a string that is present in which they have written George is 22 and Michael is 34. So as you can see what are useful data that I can find here only name and age.
    • So what I can do I can identify a pattern with the help of regular expression.
    • I can convert that to a dictionary.

    Let’s take an example to check how to remove substring from string python regex.

    Here is the screenshot of following given code.

    Remove substring from string python regex

    This is how to remove substring from string using regex in Python (python remove substring from string regex).

    Remove substring from string python DataFrame

    DataFrame is two dimensional and the size of the data frame is mutable potentially heterogeneous data. We can call it heterogeneous tabular data so the data structure which is a dataframe also contains a labeled axis which is rows and columns and arithmetic operation aligned on both rows and column tables. It can be thought of as a dictionary-like container.

    • In this section, we will learn how to remove substring from string Python DataFrame.
    • First, we have to create a DataFrame with one column that contains a string.
    • Then we have to use a string replace() method to remove substring from a string in Python DataFrame.

    Let’s take an example to check how to remove substring from string python DataFrame.

    Here is the screenshot of following given code.

    Remove substring from string python dataframe

    This is how to remove substring from string in Python DataFrame.

    Python remove substring from string by index

    Index String method is similar to the fine string method but the only difference is instead of getting a negative one with doesn’t find your argument.

    • In this section, we will learn how to remove substring from stringby index.b-1.
    • Remove substring from a string by index we can easily use string by slicing method.
    • String Slicing returns the characters falling between indices a and b.Starting at a,a+1,a+2..till b-1.

    Here is the syntax of string slicing.

    Let’s take an example to check how to remove substring from string by index.

    Here is the screenshot of following given code.

    Remove substring from string python by index

    This is how to remove substring from string by index in Python.

    Remove duplicate substring from string Python

    Let’s take an example this is a given string ‘abacd’. Now you can see that ‘a’ is repeating two times and no other character is repeating. So after removing all the duplicates. The result will be a b c d’. The condition is that you need to remove all the duplicates provided the order should be maintained.

    • In this section, we will learn how to remove duplicate substring from string python.
    • Using set() +split() method to remove Duplicate substring.

    Here is the Syntax of set() +split()

    Let’s take an example to check how to remove duplicate substring from string python.

    Here is the screenshot of following given code.

    Remove dupicate substring from string python

    The above Python code to remove duplicate substring from string in Python.

    Remove last substring from string python

    • In this section, we will learn how to remove the last substring from string Python.
    • Using the Naive method On the off chance that the first letter of the provided substring matches, we start an inner loop to check if all components from the substring match with the successive components in the main string. That is, we just check whether the whole substring is available or not.

    Let’s take an example to check how to remove the last substring from string Python.

    Here is the screenshot of following given code.

    Remove last substring from string python

    This is how to remove last substring from string in Python.

    Remove first substring from string python

    • In this section, we will learn how to remove the first substring from string python.
    • Remove the first substring from the string we can easily use string by slicing method.
    • String Slicing returns the characters falling between indices a and b.Starting at a,a+1,a+2..till b-1.

    Here is the syntax of String Slicing.

    Let’s take an example to check how to remove the first substring from string python

    Here is the screenshot of following given code.

    Remove first substring from string in python

    The above Python code we can use to remove first substring from string in Python.

    Remove substring from beginning of string python

    • In this section, we will learn how to remove substring from the beginning of string python.
    • Using loop + remove() + startswith() remove substring from beginning of string.

    Here is the syntax of loop + remove () +startswith()

    Let’s take an example to check how to remove substring from beginning of string python.

    Here is the screenshot of following given code.

    Remove substring from beginning of string python

    Python remove substring from a string if exists

    • In this section, we will learn how to remove a substring from a string if exists.
    • String replace() method remove substring from a string if exists.

    Here is the syntax of string replace

    Let’s take an example to check how to remove substring from a string if exists

    Here is the screenshot of following given code.

    Python remove substring from a string if exists

    This is how to remove substring from a string if exists in Python.

    Remove a substring from a string python pandas

    Pandas is a python library that is used for data manipulation analysis and cleaning. Python pandas are well-suited for different kinds of data such as we can work on tabular data.

    • In this section, we will learn how to remove a substring from a String Python pandas.
    • First, we have to create a Data Frame with one Column that contains a String.
    • Then we have to use a string replace() method which specified character with another specified character.

    String replace() method remove a substring from a string python pandas.

    Here is the syntax of String replace()

    Let’s take an example to check how to remove a substring from a string Python Pandas

    Here is the screenshot of following given code.

    Remove a substring from a string python pandas

    The above Python code, we can use to remove a substring from a string in python pandas.

    How to remove all occurrences of a substring from a string in python

    • In this section, we will learn how to remove all occurrences of a substring from a string in python.
    • String translate() will change the string by replacing the character or by deleting the character. We have to mention the Unicode for the character and None as a replacement to delete it from the String.
    • Use the String translate() method to remove all occurrences of a substring from a string in python.

    Let’s take an example to check how to remove all occurrences of a substring from a string in python.

    Here is the screenshot of following given code.

    Remove all occurences of a substring from a string in python

    The above Python code, we can use to remove all occurrences of a substring from a string in python.

    Python remove substring from the middle of a string

    • In this section, we will learn how to remove substring from the middle of a string.
    • The string replace() method remove the substring from the middle of a string.

    Here is the syntax of String replace

    Let’s take an example to check how to remove substring from the middle of a string.

    Here is the screenshot of following given code

    Remove substring from the middle of a string

    The above Python code, we can use to remove substring from the middle of a string in Python.

    You may like the following Python tutorials:

    In this python tutorial we learned about how to remove substring from a String in Python with the below examples:

    • How to remove substring from a String in Python
    • Remove substring from string python regex
    • How to remove substring from string python DataFrame
    • Python remove substring from string by index
    • How to remove duplicate substring from string Python
    • Remove last substring from string python/
    • How to remove first substring from string python
    • Remove substring from beginning of string python
    • Python remove substring from a string if exists
    • Remove a substring from a string python pandas
    • How to remove all occurrences of a substring from a string in python
    • Python remove substring from the middle of a string

    Fewlines4Biju Bijay

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

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

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