Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid Format Specifier with python3 F-strings

Tags:

python-3.x

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)
like image 658
3therk1ll Avatar asked Feb 26 '26 02:02

3therk1ll


1 Answers

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...

like image 89
Grzegorz Skibinski Avatar answered Feb 27 '26 23:02

Grzegorz Skibinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!