Python – json without whitespaces

|

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

I just realized that json.dumps() adds spaces in the JSON object

e.g.

{"duration": "02:55", "name": "flower", "chg": 0}

how can remove the spaces in order to make the JSON more compact and save bytes to be sent via HTTP?

such as:

{"duration":"02:55","name":"flower","chg":0}

👻 Read also: what is the best laptop for engineering students?

How do I trim whitespace from a string?

5 answers

robert By robert

How do I remove leading and trailing whitespace from a string in Python?

For example:

" Hello " --> "Hello"
" Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"
1278

Answer #1

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> " Hello ".strip()
"Hello"
>>> " Hello".strip()
"Hello"
>>> "Bob has a cat".strip()
"Bob has a cat"
>>> "   Hello   ".strip()  # ALL consecutive spaces at both ends removed
"Hello"

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
"  Hello"

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello
".strip(" ")
"Hello
"

1278

Answer #2

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as , , , f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip(" ") or my_string.lstrip(" ") or my_string.rstrip(" ") and so on.

More details are available in the docs.

How do I trim whitespace?

5 answers

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

Example: example string ‚Üí example string

1144

Answer #1

For whitespace on both sides use str.strip:

s = "  	 a string example	  "
s = s.strip()

For whitespace on the right side use rstrip:

s = s.rstrip()

For whitespace on the left side lstrip:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(" 	

")

This will strip any space, , , or characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re
print(re.sub("[s+]", "", s))

That should print out:

astringexample

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method