3therk1ll
3therk1ll

Reputation: 2441

Invalid Format Specifier with python3 F-strings

I have a small script where I am trying to embed string variable in a string for a post request. The issue I am having is that when I use the f-string formatting I am getting the below error.

richard@kali:~/Dropbox/offsec/Code/5_Bassmaster$ ./bassmaster.py 192.168.1.101
Traceback (most recent call last):
  File "./bassmaster.py", line 15, in <module>
    json = f'{"requests": [{request_1}, {request_2}, {request_3}]}'
ValueError: Invalid format specifier

This is my code. From what I understand it should be embedding said strings but I can't get rid of the error. I have tried using the ^ character as suggested here but it doesn't resolve the issue.

#!/usr/bin/python3

import requests,sys

if len(sys.argv) != 2:
    print(f"(+) usage: {sys.argv[0]} <target>") 
    sys.exit(-1)

target = f"http://{sys.argv[1]}:8080/batch"

request_1 = '{"method":"get","path":"/profile"}' 
request_2 = '{"method":"get","path":"/item"}' 
request_3 = '{"method":"get","path":"/item/$1.id"}'

json = f'{"requests": [{request_1}, {request_2}, {request_3}]}'
r = requests.post(target, json)

print(r.text)

Upvotes: 13

Views: 18296

Answers (3)

Daniel
Daniel

Reputation: 4745

For anyone looking to escape curly brackets inside format strings, you just repeat the characters:

SUBME="value"
print(f'{{ "json": {{ "key": "{SUBME}" }} }}')

{ "json": { "key": "subme" } }

Upvotes: 0

Swann_bm
Swann_bm

Reputation: 116

With json dumps:

#!/usr/bin/python3
import json
import requests
import sys

if len(sys.argv) != 2:
    print(f"(+) usage: {sys.argv[0]} <target>")
    sys.exit(-1)

r = requests.post(
    f"http://{sys.argv[1]}:8080/batch",
    json.dumps(
        {
            "requests": [
                {"method": "get", "path": "/profile"},
                {"method": "get", "path": "/item"},
                {"method": "get", "path": "/item/$1.id"},
            ]
        }
    ),
)

print(r.text)

Upvotes: 2

Georgina Skibinski
Georgina Skibinski

Reputation: 13407

Try:

json = f'"requests": [{request_1}, {request_2}, {request_3}]'
json="{"+json+"}"

Instead of the line with json = f"..."

The most outer brackets are the issue here. F-string doesn't know how to treat double brackets - so you need to make it work in a way that there are single wavy brackets opening and closing and nothing more around them...

Upvotes: 11

Related Questions