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?
Related
I need to print twin primes in the following manner
3:5,5:7,11:13,17:19
But my code is printing like this
3:5,5:7,11:13,17:19,
print("{0}: {1}" .format(n,n+2), end=', ')
I am using end=',' in the print statement and hence the comma at the last.
Is there any other way of printing
Instead of using end make a string first via a join and print that
print(", ".join(f"{n}:{n+2}" for n in my_list))
or you can print the entire list rather than iterating and printing and use sep
print(*(f"{n}:{n+2}" for n in my_list), sep=", ")
for i in range (20):
print(i, end='.')
my result is actually
0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
is there any way or advise so that my print will be
0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19
You can do this:
print(".".join(str(n) for n in range(20)))
That generates the numbers from 0 to 19 (inclusive), converts each one to a string, joins them together with . as a separator, then prints the result.
I would prefer to use the inline "if" statement.
for i in range(20): print(i, end="" if i == 19 else ".")
You can get all elements but the last one. Let's say you have that string on the variable my_str, you could try:
my_str[-1:]
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
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.
it's a loop to reverse a string entered by the user, it reads letters in reverse and put them into a sentence. the problem is that, for example user's input is hello, the comma(,) in the last line of the code makes the output to be o l l e h, but if there isnt a comma there, the output will have each letter in a line. and concatenate (+) doesnt work it gives an error. What do i do so that the output would be olleh instead of o l l e h?
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
for index in range (end,-1,-1):
print phrase[index],
how about:
string = ''
for i in range(end, -1, -1):
string += phrase[i]
print string
However, an easier, cleaner way without the for loop is:
print phrase[::-1] # this prints the string in reverse
And also there is:
#As dougal pointed out below this is a better join
print ''.join(reversed(phrase))
#but this works too...
print ''.join(phrase[i] for i in range(end, -1, -1)) # joins letters in phrase together from back to front
To concatenate something, you have to have a string to concatenate to. In this case, you need a variable that is defined outside of the for loop so you can access it from within the for loop multiple times, like this:
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
mystr = ""
for index in range (end,-1,-1):
mystr += phrase[index]
print mystr
Note that you can also simply reverse a string in Python doing this:
reversedstr = mystr[::-1]
This is technically string slicing, using the third operator to reverse through the string.
Another possibility would be
reversedstr = ''.join(reversed(mystr))
reversed returns a reversed iterator of the iterator you passed it, meaning that you have to transform it back into a string using ''.join