Skip to content
Fix Code Error

Remove all whitespace in a string

March 13, 2021 by Code Error
Posted By: Anonymous

I want to eliminate all the whitespace from a string, on both ends, and in between words.

I have this Python code:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?

Solution

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

If you want to remove all space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'
Answered By: Anonymous

Related Articles

  • Tkinter Custom Rectangle widget
  • Why does my convolutional model does not learn?
  • What are the undocumented features and limitations…
  • Multiple context menu in a single qTableView pyqt5
  • Trouble understanding behaviour of modified VGG16…
  • Combining pyOSC with pyQT5 / Threading?
  • My Button Functions Are Not Working in my Python code
  • Matplotlib plot's title is missing for unknown…
  • Can't install via pip because of egg_info error
  • Best way to replace multiple characters in a string?
  • How do I programmatically change the parent of a layout
  • Layout doesn't expand more than initial size it was…
  • How to monitor a filtered version of a metric in…
  • Replace non-ASCII characters with a single space
  • How not to get a repeated attribute of an object?
  • How to return a negative fraction when subtracting…
  • Validate that a string is a positive integer
  • Kivy WebView Error: Cannot add to window, it already…
  • How can I connect a signal to different slots…
  • Pygame Curve Movement Problem How To Fix?
  • Python-coded neural network does not learn properly
  • DQN Pytorch Loss keeps increasing
  • QGraphicsItem don't change pen of parent when chaning child
  • Import Python Script Into Another?
  • How to use QThread() within class of QWidget function?
  • How to move the player across a one background image?
  • How does the @property decorator work in Python?
  • ImportError: No module named dateutil.parser
  • Adding animation to QPushbutton enterEvent and exitEvent
  • Why Do I get a Stack Overflow error when using…
  • Resizing an image in an HTML5 canvas
  • How to get the updated entry string from a toplevel…
  • Call a method from a method of another class (Nested Class)
  • How do I create a radio button that accept user input text?
  • How to dynamically add widgets to a layout after a…
  • Start a Thread Timer directly
  • Unknown difference between logic of OOP code…
  • How to download Xcode DMG or XIP file?
  • Why doesn't my scrolbar appear after clicking the…
  • Reference - What does this regex mean?
  • In CSS Flexbox, why are there no "justify-items" and…
  • What's the difference between eval, exec, and compile?
  • PyQT5: how to automatically align the widget in QGridLayout?
  • TensorFlow 2.0 : ValueError - No Gradients Provided…
  • Tkinter understanding mainloop
  • ROS topic is not published yet
  • Tailswind css - "list-disc" is not styling bullets…
  • Elegant ways to support equivalence ("equality") in…
  • Ukkonen's suffix tree algorithm in plain English
  • Is it possible to apply CSS to half of a character?
  • Why do we use __init__ in Python classes?
  • iOS UICollectionViewCell resizable dashed border
  • Create a Custom Widget with QListWidget,QLable and…
  • Why is UICollectionViewDiffableDataSource reloading…
  • How many times the loss function is triggered from…
  • Is ASCII code 7-bit or 8-bit?
  • Usage of __slots__?
  • How to store the last checked item as default, when…
  • How to obtain the Minimum Size/Fixed Size of the…
  • I am making a browser In pyqt5, but I don't know how…
  • wxpython do action before closing wx.EVT_CLOSE
  • TypeError: Cannot convert a symbolic Keras…
  • binding backbone form view UIto model change to…
  • How to "perfectly" override a dict?
  • Smart way to truncate long strings
  • MPRemoteCommandCenter error: the track is played…
  • Make the whole gridLayoutWidget clickable
  • Deep Q Learning - Cartpole Environment
  • Python Key Error=0 - Can't find Dict error in code
  • How to perform unary operations on a class in Python?
  • Pygame Enemy not showing on screen
  • Tkinter example code for multiple windows, why won't…
  • Passing variables, creating instances, self, The…
  • Force encode from US-ASCII to UTF-8 (iconv)
  • Javascript Uncaught TypeError: Cannot read property…
  • Moving cursor to first entry box pyqt5
  • PyQt5 add text over browser page
  • What are type hints in Python 3.5?
  • Cant wrap my head around Classes and Kivy
  • Donut piechart in mplcanvas
  • Undefined Reference to
  • Removing leading and trailing spaces from a string
  • Implement LRU cache with using…
  • How do I bind the enter key to a function in tkinter?
  • EXP system for adjusting instance attributes in…
  • What does Ruby have that Python doesn't, and vice versa?
  • How to make prediction on pytorch emotion detection model
  • Calculate an area using property method in Python
  • How can I wrap all BeautifulSoup existing…
  • set variable network layers based on parameters in pytorch
  • Django - update inline formset not updating
  • How to access MainThread elements from different thread?
  • What encoding/code page is cmd.exe using?
  • Switch between two frames in tkinter
  • How to print a 'particular' element in a list (not…
  • How do I trim whitespace from a string?
  • Replacing nested loops over a dataframe with…
  • Download & Install Xcode version without Premium…
  • Python 3 TypeError: must be str, not bytes with…
  • How to update Python?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to remove focus border (outline) around text/input boxes? (Chrome)

Next Post:

How to import other Python files?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error