简体   繁体   English

在同一行上多次打印字符串

[英]Print String multiple times on the same line

I am trying to print a string, multiple times together on the same line. 我试图在同一行上多次打印字符串。

For example: User input = 123 and I need to print it 3 times: 123123123 例如:用户输入= 123,我需要打印3次:123123123

This is my code that i have tried: 这是我尝试过的代码:

userString = []

    if val > 0:
    for i in range(val):
        print(userString * val, end = " ")

it's giving me a syntax error by the end="" 它通过end =“”给了我一个语法错误

How can I fix this? 我怎样才能解决这个问题?

if val > 0:
   print('%s ' % userString * val)

You are using python 2 not python 3 , you can either use: 您使用的是python 2而不是python 3,您可以使用:

from __future__ import print_function # import the print function 

Or use: 或使用:

print(userString * val), # <- trailing comma 

You could also use join and a list comprehension to match the output of your python 3 print code: 您还可以使用join和list comprehension来匹配python 3打印代码的输出:

val = 5
print(" ".join(["*" * val for _ in range(val)])) if val else ""
***** ***** ***** ***** *****

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

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