Formatting: multiple print statements without spaces - python

I'm trying to print multiple things scattered in a loop. Here is an example:
print str(n)+" ",
for I in range(k):
print str(l)+"+",
if l>4:
break
This gives me an out put like
10= 1+ 2+ 3+ 4
While I want it to give
10=1+2+3+4

Use sys.stdout.write directly instead of print:
from sys import stdout
stdout.write(str(n)+" ")
for I in range(k):
stdout.write(str(l)+"+")
if l>4:
break

The reason this happens is because a comma with the print statement forces a space between the two elements. You're best to construct the target output string inside the loop, then print it once. Try to avoid any sort of output being done in a loop if possible.
outstr = str(n)+" " # do you mean `str(n)+"="?`
for I in range(k):
outstr = outstr + str(l)+"+",
if l>4:
break
print outstr

Related

How to remove last blank from printed line in python3?

I want to remove the last blank from printed line.
example)
list=[1,2,3,4]
for i in range(2):
print(list[i], end=" ")
>>> 1 2
There is a one blank after '2' in printed line. How can I modify the code to remove the last blank?
You can also use "list unpacking" similar to Unpacking Argument Lists in conjunction with slices.
For example:
print(*list[:2])
Returns:
1 2
+ new line symbol \n
To remove the \n symbol, you can use this code.
print(*list[:2], end="")
You can do this " ".join(map(str, [list[i] for i in range(2)])).
The blank is due to the argument end = " " in print function. This essentially tells the python program to add a " " (blank) instead of newline after every print. So you can either remove it or do something like this in your for loop.
list = [1, 2, 3, 4]
for i in range(2) :
if (i != range(2)[-1]) :
print (list[i], end = " ")
else :
print (list[i], end='')
This tells the python program to not use the extra space or newline at the end of for loop.
You don't need a for loop for this
a=[1,2,3,4]
b=' '.join(map(str,a[:2]))
will do
list=[1,2,3,4]
for i in range(2):
if i == max(range(2)):
print(list[i])
else:
print(list[i], end=" ")
1 2
If you mean you always want to cut the last space but keep the others, how about adding if?

How to print two statements from different functions on the same line in Python

I'm trying to print two output statements on the same line in Python 2.7 (or 3.4). The print statements don't come one after the other Like print a/ print b. My program takes 329 (say) and returns that value in words - three hundred twenty nine. So it will determine the 300 part and print it then the 29 part and print that.
if (main == hundreds[index]):
print hundreds_words[index]
for location in range (0, 10):
if (difference == twenties[location]):
print twenties_words[location]
I want to print the twenty nine on the same line as the three hundred. I suppose I could try and rig up a solution but I would like to know if Python has a procedure to do that.
Yes, it does. You just need to tell print not to add a new-line after the first one. In python2, you do this by adding a trailing comma: print mystring,. In python3, print is a function that has the end keyword argument: print(mystring, end="")
The easy way is to rewrite your number-to-words function and have it return a string instead of printing it.
The more involved way is to redirect stdout to capture the print output as a string.
Edit: looks like I made it more complicated than necessary; you could instead try
output_words = []
if (main == hundreds[index]):
output_words.append(hundreds_words[index])
for location in range (0, 10):
if (difference == twenties[location]):
output_words.append(twenties_words[location])
return " ".join(output_words)
In python 2 you can end a print statement with a , to indicate not to terminate in a newline, e.g.:
print hundreds_words[index],
In python 3 (or py2 with from __future__ import print_function) you explicitly need to define the end, e.g.:
print(hundreds_words[index], end=' ')
But ideally you would just collect all the result up in a list and join() them at the end...
result = []
if (main == hundreds[index]):
result.append(hundreds_words[index])
for location in range (0, 10):
if (difference == twenties[location]):
result.append(twenties_words[location])
print(' '.join(result))
Always design functions to return values, and not to print them (it's much more Pythonic!). Therefore, you should modify your code this way:
# FOR PYTHON 2.x
if (main == hundreds[index]):
print hundreds_words[index], # Note the comma
for location in range (0, 10):
if (difference == twenties[location]):
print twenties_words[location]
# FOR PYTHON 3.x
if (main == hundreds[index]):
print(hundreds_words[index], end=" ") # end=" " will override the default '\n' and leave a space after the string
for location in range (0, 10):
if (difference == twenties[location]):
print(twenties_words[location])
There's also a third option, more scalable: to wrap all datas in a list, and then print everything.
printable = []
if (main == hundreds[index]):
printable += hundreds_words[index]
for location in range (0, 10):
if (difference == twenties[location]):
printable += twenties_words[location]
print(" ".join(printable))

Python Printing and multiplying strings in Print statement

I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return

Printing Out Every Third Letter Python

I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.'
This is my code:
text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
decoded = text[i]
print(decoded, end=" ")
Although I it says it isn't correct, it say this is the desired out-put:
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?
To have spaces only between the characters, you could use a slice to create the string "challenge" then use str.join to add the spaces:
" ".join(text[::3])
Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"
So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:
line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
result += ' ' + line[i]
print(result)
Or this:
line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
print(' ' + line[i], end='')
print()
Or maybe this:
code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])
All of these should work, and I hope this answers your question.
I think Grok is just really picky about the details. (It's also case sensitive)
Maybe try this for an alternative because this one worked for me:
message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
decoded += message[i] + ' '
print(decoded.rstrip())
You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.
Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.
output = ""
for i in range(10):
output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())
If you look through the Grok course, there is one page called ‘Step by step, side by side’ (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.

Advice on python program

So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")

Categories