【问题标题】:How do I add numbers and spaces to my typing function in Python?如何在 Python 中向我的键入函数添加数字和空格?
【发布时间】:2022-12-10 19:52:25
【问题描述】:

考虑到我昨天刚刚在这里问了一个问题并在 3 分钟内得到了有用的答案,我决定再问一个。 我的类型函数(功能类似于打印,但单独键入每个字符)现在可以接受多个参数。但是,现在我需要它接受数字,这是一个问题,因为整数是不可迭代的。因此,我需要一种方法来在我的函数中将 int 干净地转换为 str。 另外,我需要一种在每个参数之间放置空格的方法。

我当前的代码是:

def type(*text):
  for string in text:
    for char in string:
      sys.stdout.write(char)
      sys.stdout.flush()
      time.sleep(0.05)
  print()

应用标准的 str() 函数会在我的输入周围产生方括号和单引号,有什么方法可以干净地转换它吗? 此外,目前参数之间没有间距,因此输入:

type("hello",name)

将产生以下输出: 你好(在这里插入名字) 我也很感激有办法解决这个问题。
谢谢你。

【问题讨论】:

  • 对于空格,请使用 " ".join( *words, go, here*) 要将 int 转换为 str,请执行 str(myint)
  • 如果您希望参数为int,您应该显示您尝试过的内容,并且可能会出现错误,因此您也应该显示它。

标签: python


【解决方案1】:
def type_char(*text):
    for string in text:
        if string is not isinstance(string, str):
            string = str(string)
        string += " "
        for char in string:
            sys.stdout.write(char)
            sys.stdout.flush()
            time.sleep(0.05)
    print()


>>> type_char("hello", 5, "world")
hello 5 world 

【讨论】:

    【解决方案2】:

    您可以像这样在每个单词后添加一个空格:

    import time
    import sys
    
    def type(*text):
        for string in text:
            for char in string:
                sys.stdout.write(char)
                sys.stdout.flush()
                time.sleep(0.05)
            sys.stdout.write(" ")
        print()
    
    
    name = "hugo"
    type("hello", name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 2021-12-06
      • 2022-07-25
      相关资源
      最近更新 更多