Python: How do I get user input in the middle of a sentence (fill-in-the-blank style) using the input function?

て烟熏妆下的殇ゞ 提交于 2019-11-30 09:45:47

问题


I am trying to create a program that calculates sales tax. I first ask the user what was the total cost of their meal. I then ask them what is the sales tax of their area in the form of:

y = input('What is the sales tax of your area? ')

I want to have a percent sign "%" at the end of the question so that the users sees the question as:

What is the sales tax of your area?_% , where the user can enter a number between the question and the percent sign (denoted by the underline).

This is what I have tried:

x = float(input("What is the cost of your meal? "))
y = input("What is the sales tax in your area? "+"%")

float(y)
y = y/100
cost = (x+(x*y))

print("The cost of your food is " + cost)

回答1:


you can do something like this

x=input("What is the sales tax in your area?    % \x1B[5D")

it first print the line and then the escape sequence \x1B[5D moves the cursor 5 place backwards. But what the 1st answer says, you can not do this without knowing beforehand how long the input is going to be. If it is longer then it will overwrite the percentage sign. you can check here for more such escape sequence

Also if you don't want this very much urgently then I would suggest you to ask the user to input in percentage form instead of putting a % sign at the end of inpur




回答2:


I have a solution for you. Just a trick, didn't find direct solution even after searching for long. But one thing is for sure, you need to know the length of input, else for very long input the ! will be overwritten. Code below:

x = float(input("What is the cost of your meal? "))
y = input("What is the sales tax in your area?  %\rWhat is the sales tax in your area?")

y = float(y)/100
cost = (x+(x*y))

print("The cost of your food is ", cost)



回答3:


You can't do that with input() without knowing how long the input will be. You could just ask the user to answer in percent. You could use ANSI escape codes to put the percent sign after the place where you get input, but it will be overwritten if you type until you reach the percent sign. If you really need that, then you could use curses for the whole thing.



来源:https://stackoverflow.com/questions/38246529/python-how-do-i-get-user-input-in-the-middle-of-a-sentence-fill-in-the-blank-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!