Search code examples
pythonpython-3.xformattingformat

Python: Format headers


So I have some headers that I need to format automatically. I have always done it manually and It's getting boring now and I'm searching for a way to do it automatically. I have tried using Python built in formatting but that didn't work.

These are the headers:

headers = {
    authority: discord.com
    method: POST
    path: /api/v9/auth/register
    scheme: https
    accept: */*
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9
    content-length: 2840
    content-type: application/json
    origin: https://discord.com
    referer: https://discord.com/register
    sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
    sec-ch-ua-mobile: ?0
    sec-ch-ua-platform: "Windows"
    sec-fetch-dest: empty
    sec-fetch-mode: cors
    sec-fetch-site: same-origin
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
    x-debug-options: bugReporterEnabled
    x-discord-locale: en-US
}

And i'm looking to format them like this:

    "authority": "discord.com",
    "method": "POST",
    "path": "/api/v9/auth/register",

Solution

  • You can do special formatting using something called a regular expression. Some IDE's support using these, and PyCharm is one of them.

    Here are the steps:

    1. Press Ctrl + R and select the star button at the end of the first row
    2. Type in first row: ^\s+(.+): (.+) and in the second row: '$1': '$2',
    3. Press Replace All and exit out of the replace tool window
    4. Press Ctrl + Alt + L to reformat the dictionary

    You can remove the comma on the last item in dictionary if desired. I used apostrophes instead of quotation marks because some of the items have quotes.

    enter image description here