dav
dav

Reputation: 43

Can I position input inside of a string in python?

I am trying to position an input within a string in python.

For example, the console will read "I am ___ years old", and the input value completes the sentence. Is there a way to do this?

Upvotes: 0

Views: 1345

Answers (4)

Arty
Arty

Reputation: 16737

One more solution using console ANSI escape chars and module ansicon (needs once installing through python -m pip install ansicon), besides moving cursor it will also give nice things like coloring, etc. Escape chars thanks to this module will work both in Unix and Windows systems. Unix supports escape chars natively even without this module.

# Needs: python -m pip install
import ansicon
ansicon.load()

age = int(input('I am ___ years old' + '\x1b[D' * 13))
print('Your age is:', age)

Using escape chars many things can be done, e.g. coloring word years in green, using next line of code:

age = int(input('I am ___ \x1b[32myears\x1b[m old' + '\x1b[D' * 13))

which outputs:

img

Unix systems need no modules at all, thus code can be just two lines, this code you can see and try here online!

Color table for standard set of colors can be easily printed by next code, these numbers should be placed instead of 32 in code \x1b[32m above:

for first, last in [(30, 47), (90, 107)]:
    for color in range(first, last + 1):
        print(f'\x1b[{color}m{str(color).rjust(3)}\x1b[m ', end = '')
    print()

which outputs:

enter image description here

Upvotes: 1

user_input = ("how old are you ? : ")
print("you are ",user_input"," this old !")

Upvotes: 0

datamansahil
datamansahil

Reputation: 412

This should solve your problem.

words_list= ["I","am","x","years","old"] # sentence having missing value as "x"
val = input("how many years old are you ?") # input the value of "x"
words_list[2] = val # replace the value of "x" at right place
print(' '.join(word for word in words_list)) # get the output with missing owrd at right place as sentence

Upvotes: 0

tobias_k
tobias_k

Reputation: 82899

Not entirely sure what you want. If you just want the input to be placed into that string, you can, among others, use the new format strings (or just str.format, or the % operator):

age = input("What is your age? ")
print(f"I am {age} years old")

If your string actually has that ___ section and you want to insert the age there, you can first replace that with a proper format symbol and then use format:

import re
s = re.sub("_+", "{}", "I am ___ years old")
print(s.format(age))

If, as some suggested in comments, you might actually want the user to fill in the blank as they type, you can first print the line, then use \r and flush to go back to the beginning and then ask for the input, overwriting just as much so that the input cursor is on the ___ part.

print("I am ___ years old", end="\r", flush=True)
age = input("I am ")
print(age)

Upvotes: 1

Related Questions