Home > OS >  How to get value of input within same print call?
How to get value of input within same print call?

Time:12-13

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.

CodePudding user response:

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

CodePudding user response:

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')

CodePudding user response:

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")
  • Related