简体   繁体   English

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

[英]How to print output of for loop on same line

Here is my code:这是我的代码:

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)

How to get output characters printed in same line?如何在同一行打印输出字符?

I see 3 issues in your program -我在你的程序中看到 3 个问题 -

  1. In the for loop in second line , you have missed closing a bracket - for i in range (len(str): , it should be - for i in range (len(str)):在第二行的for循环中,您错过了关闭括号 - for i in range (len(str): ,它应该是 - for i in range (len(str)):

  2. There is no casting in python, to convert input to string, you have use int function, as int(...) , so your line (int)(input(...)) should be - int(input(...)) . python 中没有casting转换,要将输入转换为字符串,您使用int函数,如int(...) ,因此您的行(int)(input(...))应该是 - int(input(...))

  3. In your for loop, you are defining the index as i , but you are using ch inside the loop, you should be using i instead of `ch.在您的 for 循环中,您将索引定义为i ,但您在循环内使用ch ,您应该使用i而不是 `ch。

Example -例子 -

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

The print statement to print items without appending the newline is fine, it should be working.在不附加换行符的情况下打印项目的打印语句很好,它应该可以工作。

A working example -一个工作示例 -

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

To print on one line, you could append each letter on a string.要在一行上打印,您可以将每个字母附加到一个字符串上。

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

I'm new into python and my friend is giving me tasks to perform and one of them was to print a square made out of "*" and this is how I did it:我是 python 新手,我的朋友给了我要执行的任务,其中之一是打印一个由“*”组成的正方形,我就是这样做的:

br = int(input("Enter a number: "))

for i in range(0, br):
    print("*" * br)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM