简体   繁体   中英

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 -

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

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

  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.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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