【问题标题】:Can I position input inside of a string in python?我可以将输入定位在python中的字符串内吗?
【发布时间】:2020-10-01 09:50:24
【问题描述】:

我正在尝试在 python 中的字符串中定位输入。

例如,控制台会读取“我是 ___ 岁”,输入值完成句子。有没有办法做到这一点?

【问题讨论】:

  • 请更新问题以显示您迄今为止尝试/研究的内容。你被困在哪里了?提示:查找str.replace 或“字符串格式”。
  • 尝试格式化字符串,例如f"I am {the_input_string} years old"。或者你的意思是输入应该放在字符串中当用户输入它时,即有一个包含输入的输入提示?
  • 我认为作者的意思是输入光标应该放在句子中间。
  • 我怀疑答案并不像某些人认为的那么简单。我认为@dav 要求在用户键入时填写空白。
  • 问题的答案是是的,有办法。如果你想要更多,你应该显示你当前的代码。

标签: python python-3.x string input


【解决方案1】:

不完全确定你想要什么。如果您只想将输入放入该字符串中,您可以使用新的格式字符串(或仅使用 str.format% 运算符):

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

如果您的字符串实际上有 ___ 部分并且您想在其中插入年龄,您可以先将其替换为适当的格式符号,然后使用 format

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

如果按照 cmets 中的一些建议,您可能确实希望用户在键入时填写空白,您可以先打印该行,然后使用 \rflush 回到开头,然后要求输入,尽可能多地覆盖以使输入光标位于___ 部分。

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

【讨论】:

  • 谢谢,第二个选项就是我的意思,解决了。
  • @dav 实际上我只是插入了一个新的第二个选项。你的意思是,还是现在的第三个选项?
【解决方案2】:

使用console ANSI escape chars 和模块ansicon 的另一种解决方案(需要通过python -m pip install ansicon 安装一次),除了移动光标之外,它还可以提供诸如着色等不错的功能。由于该模块,转义字符可以在Unix 中使用和 Windows 系统。即使没有这个模块,Unix 本身也支持转义字符。

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

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

使用转义字符可以做很多事情,例如使用下一行代码将years 着色为绿色:

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

哪个输出:

Unix系统根本不需要模块,因此代码可以只有两行,这段代码你can see and try here online!

标准颜色组的颜色表可以通过下一个代码轻松打印,这些数字应放置在上面的代码\x1b[32m中而不是32

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

哪个输出:

【讨论】:

    【解决方案3】:

    这应该可以解决您的问题。

    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
    

    【讨论】:

      【解决方案4】:
      user_input = ("how old are you ? : ")
      print("you are ",user_input"," this old !")
      

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 2011-08-19
        • 2020-03-11
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多