-2

I have the following code in Python 3

def inputWithDefault(text:str, default):
    result = input(f"{" " * int(len(text))}{default}\r{text}")
    return default if not(result is type(default)) else result

Python says this when in the syntax-tree generation stage

  File "main.py", line 2
    result = input(f"{" " * int(len(text))}{default}\r{text}")
                                                             ^
SyntaxError: f-string: expecting '}'

This is difficult to work through as the error is unclear and its reasoning is difficult to parse, I have checked and the {} match up throughout the fstring declaration.

4
  • Your problem is that f"{" does not contain a closing }. You have two string literals there and the f applies only to the first. I can't really tell what you're trying to do or why you wrote it as two separate string literals, so I can't advise you further on that. Commented Sep 30, 2024 at 16:27
  • 3
    Your f-string has nested double quotes: ". You need python 3.12 or better to parse that. Commented Sep 30, 2024 at 16:33
  • 1
    What's the question? For example, maybe you want to ask why this error is occurring when the braces are in fact balanced. Please edit to clarify and write a more specific title. (On that note, input() is irrelevant to the problem.) For tips, see How to Ask. Commented Sep 30, 2024 at 17:07
  • 2
    BTW, the last line of your code doesn't make any sense. result is type(default) will never be true because result is always a string, never a type. If you want an actual (editable) default value to input(), see Show default value for editing on Python input possible? or (non-editable) How to define default value if empty user input in Python? Commented Sep 30, 2024 at 17:20

2 Answers 2

1

I have moved the spaces at the start into a variable spacing like so removing the errors

def inputWithDefault(text:str, default):
    spacing = " " * int(len(text))
    result = input(f"{spacing}{default}\r{text}")
    return default if not(result is type(default)) else result
Sign up to request clarification or add additional context in comments.

Comments

1

you can use single quotes on the inside

def inputWithDefault(text: str, default):
    result = input(f"{' ' * int(len(text))}{default}\r{text}")
    return default if not isinstance(result, type(default)) else result

1 Comment

Why did you change the type check? That's irrelevant to the problem. (Also, I don't think this technique even works, but I'm not totally sure what OP intended to do.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.