Python удалить символы между

Python strip() – How to Trim a String or Line

Dionysia Lemonaki

Dionysia Lemonaki

Python strip() – How to Trim a String or Line

In this article, you’ll learn how to trim a string in Python using the .strip() method.

You’ll also see how to use the .lstrip() and .rstrip() methods, which are the counterparts to .strip() .

How to trim a string in Python

Python has three built-in methods for trimming leading and trailing whitespace and characters from strings.

Each method returns a new trimmed string.

How to Remove Leading and Trailing Whitespace from Strings in Python

When the .strip() method has no argument, it removes any leading and/or trailing whitespace from a string.

So, if you have whitespace at the start and/or end of a word or phrase, .strip() alone, by default, will remove it.

The following variable greeting has the string «Hello» stored in it. The string has space both to the right and left of it.

greeting = " Hello! " print(greeting,"How are you?") #output # Hello! How are you? 

To remove both of them, you use the .strip() method, like so:

greeting = " Hello! " stripped_greeting = greeting.strip() print(stripped_greeting,"How are you?") #output #Hello! How are you? 

You could have also used the .strip() method in this way:

greeting = " Hello! " print(greeting.strip(),"How are you?") #output #Hello! How are you? 

How to Remove Leading and Trailing Characters from Strings in Python

The .strip() method takes optional characters passed as arguments.

The characters you add as arguments specify what characters you would like to remove from the start and end of the string.

Below is the general syntax for this case:

The characters you specify are enclosed in quotation marks.

Читайте также:  Анимация для border css

So, for example, say you have the following string:

You want to remove «H» and «?», which are at the beginning and at end of the string, respectively.

To remove them, you pass both characters as arguments to strip() .

greeting = "Hello World?" stripped_greeting = greeting.strip("H?") print(stripped_greeting) #output #ello World 

Notice what happens when you want to remove «W» from «World», which is at the middle and not at the start or end of the string, and you include it as an argument:

greeting = "Hello World?" stripped_greeting = greeting.strip("HW?") print(stripped_greeting) #ello World 

It will not be removed! Only the characters at the start and end of said string get deleted.

That being said, look at the next example.

Say you want to remove the first two and the last two characters of the string:

phrase = "Hello world?" stripped_phrase = phrase.strip("Hed?") print(stripped_phrase) #output #llo worl 

The first two characters («He») and the last two («d?») of the string have been removed.

Another thing to note is that the argument does not remove only the first instance of the character specified.

For example, say you have a string with a few periods at the beginning and a few exclamation marks at the end:

When you specify as arguments . and ! , all instances of both will get removed:

phrase = ". Python . " stripped_phrase = phrase.strip(".!") print(stripped_phrase) #output #Python 

How to Remove Only Leading Whitespace and Characters from Strings in Python

To remove only leading whitespace and characters, use .lstrip() .

This is helpful when you want to remove whitespace and characters only from the start of the string.

An example for this would be removing the www. from a domain name.

domain_name = "www.freecodecamp.org www." stripped_domain = domain_name.lstrip("w.") print(stripped_domain) #output #freecodecamp.org www. 

In this example I used the w and . characters both at the start and the end of the string to showcase how .lstrip() works.

If I’d used .strip(w.) I’d have the following output:

The same goes for removing whitespace.

Let’s take an example from a previous section:

greeting = " Hello! " stripped_greeting = greeting.lstrip() print(stripped_greeting,"How are you?" ) #output #Hello! How are you? 

Only the whitespace from the start of the string has been removed from the output.

How to Remove only Trailing Whitespace and Characters from Strings in Python

To remove only trailing whitespace and characters, use the .rstrip() method.

Say you wanted to remove all punctuation only from the end of a string.

You would do the following:

enthusiastic_greeting = ". Hello . " less_enthusiastic_greeting = enthusiastic_greeting.rstrip("!") print(less_enthusiastic_greeting) #output #. Hello 

Taking again the example from earlier, this time the whitespace would be removed only from the end of the output:

greeting = " Hello! " stripped_greeting = greeting.rstrip() print(stripped_greeting,"How are you?") #output # Hello! How are you? 

Conclusion

And there you have it! You now know the basics of how to trim a string in Python.

  • Use the .strip() method to remove whitespace and characters from the beginning and the end of a string.
  • Use the .lstrip() method to remove whitespace and characters only from the beginning of a string.
  • Use the .rstrip() method to remove whitespace and characters only from the end of a string.
Читайте также:  Variable not defined javascript

If you want to learn more about Python, check out freeCodeCamp’s Python Certification. You’ll start learning in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Источник

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.

Читайте также:  Where python module installed

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!

Источник

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