如何在同一行上打印for循环的输出

时间:2015-07-02 07:22:26

标签: python

这是我的代码:

def missing_ch(number, string):
      for i in range(len(string)):
        if i==number:
           continue
        else:   
           print(string[i], end=' ')
      return
string='hello'
num=int(input("enter the position of char"))
missing_ch(num, string)

如何在同一行中输出输出字符?

3 个答案:

答案 0 :(得分:0)

我在你的程序中看到3个问题 -

  1. 在第二行的for循环中,您错过了关闭括号 - for i in range (len(str):,它应该是 - for i in range (len(str)):

  2. python中没有casting,要将输入转换为字符串,您使用int函数作为int(...),因此您的行(int)(input(...))应该是 - int(input(...))

  3. 在for循环中,您将索引定义为i,但在循环中使用ch,您应该使用i而不是`ch。

  4. 示例 -

        for i in range (len(str):
            if(i==num):
                continue
            print(str[i],end=' ')
        return
    

    打印项目而不附加换行符的print语句很好,应该可以正常工作。

    一个工作示例 -

    >>> def foo():
    ...     print("Hello",end=" ")
    ...     print("Middle",end=" ")
    ...     print("Bye")
    ...
    >>> foo()
    Hello Middle Bye
    

答案 1 :(得分:0)

要在一行上打印,您可以在字符串上附加每个字母。

def missing_ch(num, str):
  result = ""
  for i in range (len(str)):
    if (i == num):
      continue
    result+=str[i]
  print result

string = 'hello'
num = (int)(input('enter the position of char'))

missing_ch(num, string)

#>helo

答案 2 :(得分:-1)

我是python的新手,我的朋友正在给我执行任务,其中之一是打印由“ *”制成的正方形,这是我的方法:

<table id="table" 
    ...
    data-escape="false"
>
相关问题