how print in python loop with space and without new line
Try this:
num = [4 , 2]
for item in num:
for i in range(item):
print(item, end=" ")
print()
Edit:
I think it's overcomplicated for a problem like this, but you can try (it shouldn't print extra space at the end):
num = [4 , 2]
for item in num:
for i in range(item):
if item - 1 == i:
print(item)
else:
print(item, end=" ")
It prints an item with a new line when it's the last number in the second loop otherwise it prints the number with a space.
Python print statement adds spaces between arguments
The python print function automatically adds a space between arguments. You should concatenate (join) the strings together and then print them
print("a","b") # a b
print("a" + "b") # ab
In python, you can use "f-strings" which are a way to "template" the string. text inside of {}
is treated like python, so you can put variables in there.
print(f"Hello {name}! You are {age} nice to meet you!")
f-strings are the best approach in python, but the first solution with "+" will work just fine for this use-case
How to remove an empty space before full stop in print () in Python [from a specified argument]
print
in Python can accept any number of arguments, and it will output all the values separated with a space by default. You can either change this separator to something else, or combine some of the output into a string
(so you will dictate if it has a space or not), or use string formatting, or something else.
For example:
print ('The sum of', firstNumber, 'and', secondNumber, 'is', str(resultingNumber) + '.');
How to print a space between each letter of a word in a list on a new line?
You could use str.join()
sentence = ["This","is","a","short","sentence"]
for w in sentence:
print(' '.join(w))
Related Topics
Remove White Space from Entire Dataframe
Django: Check Whether an Object Already Exists Before Adding
Taking Data from Drop-Down Menu Using Flask
What Is the Fastest Way to Stack Numpy Arrays in a Loop
Pandas - Find Rows With Matching Values in Two Columns and Multiply Value in Another Column
How to Perform Union on Two Dataframes With Different Amounts of Columns in Spark
How to Remove Words in a Column in Pandas
Python - How to Make User Input Not Case Sensitive
How to Remove Any Url Within a String in Python
How to Run Python Script from Another Machine Without Installing Imported Modules
Get the Row(S) Which Have the Max Value in Groups Using Groupby
How to Delete the Words Between Two Delimiters
Python: Plotting Percentage in Seaborn Bar Plot
Python Json.Loads Valueerror, Expecting Delimiter