Googled the strip ()
function, but it only removes the first and last space, and I need everything.
For example, if a = 'sd dfsdf dfsfs'
, then you need to get a = 'sddfsdfdfsfs'
.
Is there such a function or is it necessary to do something through the loop?
Answer 1, authority 100%
a.replace ('', '')
Answer 2, authority 67%
strip ()
can remove not only whitespace, but tabs and other characters that are considered whitespace, including Unicode whitespace, if strip ()
is called on a Unicode string:
& gt; & gt; & gt; import string
& gt; & gt; & gt; string.whitespace
'\ t \ n \ x0b \ x0c \ r'
& gt; & gt; & gt; string.whitespace.strip ()
''
& gt; & gt; & gt; import sys
& gt; & gt; & gt; s = '' .join (unichr (i) for i in xrange (sys.maxunicode) if unichr (i) .isspace ())
& gt; & gt; & gt; s [: 15]
u '\ t \ n \ x0b \ x0c \ r \ x1c \ x1d \ x1e \ x1f \ x85 \ xa0 \ u1680 \ u180e \ u2000'
& gt; & gt; & gt; s.strip ()
u ''
Therefore, an analogue of strip ()
that removes whitespace in the entire line: s = '' .join (s.split ())
.
Or, the same thing, using regular expressions: s = re.sub (r '\ s +', '', s, flags = re.UNICODE)
.
Or, in code where performance is important, bytes.translate ()
can be used to remove all standard (string.whitespace
in C locale) whitespace from ascii lines:
& gt; & gt; & gt; b'a \ tb \ nc'.translate (None, b '\ t \ n \ v \ f \ r')
'abc'
Answer 3, authority 11%
If you have something like this
"def m e gaDifficu ltFun ction (x):")
and want to give
def m e gaDifficu ltFun ction (x):
then you can solve by using join () and split () methods:
return "" .join (code.split ())
Answer 4, authority 6%
If you don’t know the number of spaces and tabs, the easiest way is:
a = 'Some string with meny space or tabs'
b = a.split ()
b = '' .join (b)
b & gt; & gt; & gt; Somestringwithmenyspaceortabs