How to get value of input within same print call?

Question:

Example of what I want/have:

print(input('> Discord Webhook: '), f'{"None" if len(input) < 1 else input}')

I want it to print None if the input value is less than 1, or else just print the output normally.

Asked By: vlone

||

Answers:

If you want just to print None in place of an empty string you can do that with a simple or:

print(input('> Discord Webhook: ') or None)

Note that this does not actually capture the input for you to use on a later line. Usually when you call input() you want to assign its result to a variable:

webhook = input('> Discord Webhook: ') or None
print(webhook)
# do whatever else you're going to do with that value
Answered By: Samwise

I was able to accomplish this by making it appear like the input was changed to none using the clear command and printing the input text with "None" after it.

import os
webhook = input('> Discord Webhook: ')
if len(webhook) < 1:
  os.system('clear')
  print('> Discord Webhook: None')
Answered By: vlone

If you want to change what shows up in terminal where input was given, you can use ANSI escape codes to control the cursor directly. This way you can edit specific parts of the terminal output after they have already been printed.

prompt = '> Discord Webhook: '
webhook = input(prompt)
if not webhook:
    print('u001b[1A', end = "") # Move cursor one line up
    print(f'u001b[{len(prompt)}C', end = "") # Move cursor past prompt
    print('u001b[0K', end = "") # Clear rest of line
    print("None")

On Windows you might need to do the following for cmd to recognise ANSI codes properly:

import os
os.system("")
Answered By: matszwecja
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.