I am trying to remove the spaces that appear after the output of the code. I have tried to use the .rstrip but it doesn't seem to work.
The coding is:
msg = Tjghksikdsiiireskfafslweicfnareodorffqecproerdtre
var1 = 0
var2 = 1
for i in range(len(msg)):
print(msg[var1:var2], end=' ')
var1 = int(var1) + 3
var2 = int(var2) + 3
It produces the correct coding apart from that it has lots of extra spaces at the end. Is there a way to fix this?
The output produces:
T h i s i s a l i n e o f c o d e
like it is supposed to but it adds alot of spaces after. Please help.
the extra spaces are because you are trying to print every third character but it is repeating once for every character, you can just change your for loop to this:
for i in range( int(len(msg) /3) +1):
Related
I came across this snippet on Grepper:
line = "<html><head>"
d = ">"
s = [e+d for e in line.split(d) if e]
print(s)
#Output:
#["<html>", "<head>"]
It works fine for the example given. But if I split a sentence, this snippet will add the delimiter twice:
line = "<html><head>"
d = ">"
s = [e+d for e in line.split(d) if e]
print(s)
#Output:
#['There are two methods:', ' one is to try, the other is to not try.:']
so I worked on it and came up with this, which works:
d = ","
splitSentences = sentence.split(d)
counter = 0
maxLines = len(splitSentences)
for splitSentence in splitSentences:
if counter < maxLines - 1:
paragraphList.append(splitSentence + d)
else:
paragraphList.append(splitSentence)
counter = counter + 1
I'm wondering if there is a way to do this in more elegant way.
Try this:
s = line.replace("><", ">#<").split("#")
It adds a character to the thing you want to split by, and then splits by that character so you don't lose the delimiter. Might want to use a more specific character or multiple characters though so it does't split at a different "#" by accident.
s = [e+d for e in line.split(d) if e]
# If the delimiter is not the last character, then drop it from the last string.
if line[-1] != d:
s[-1] = s[-1][:-1]
IMO, This is more readable than any one-line solution.
I keep getting syntax errors in my print command (that's why the bracket is on the one at the bottom) and I also get an End of File error (unexpected end of file while parsing) if I try to run the code.
I put a bracket on the print statement, and I have tried re-typing the code with no success.
print ("input a number")
a = (str(input(''))
if 9 in (a)
(b = a.count('9')
if 8 in (a)
(c = a.count('8')
if 7 in (a)
(d = a.count('7')
if 6 in (a)
(e = a.count('6')
if 5 in (a)
(f = a.count('5')
if 4 in (a)
(g = a.count('4')
if 3 in (a)
(h = a.count('3')
if 2 in (a)
(i = a.count('2')
if 1 in (a)
(j = a.count('1')
if 0 in (a)
(k = a.count('0')
(print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 26
^
SyntaxError: unexpected EOF while parsing
Notice the code is only 25 lines long - I haven't even opened it to 26 lines
---------------------------------------------------------------------------
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 25
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
^
SyntaxError: invalid syntax
This is what I get if I remove the bracket from the print statement.
So, the syntax error is actually because you're not ending your if statements with : and also you have a bunch of open brackets on each line in the if blocks. You may want to look at a tutorial for basic Python syntax.
The reason the syntax error doesn't happen immediately is because of how Python works. If we remove the linebreaks:
if 9 in (a)(b = a.count('9') if 8 in (a)(c = a.count('8') ...
What this does is it tries to test if 9 is in the right expression, which is a function call. It tries to call a as a function with the keyword argument b equal to a.count('9') if <expr> else <expr>, which is Python's ternary expression syntax. At the very end, it says "unexpected EOF" because it's expecting more close brackets because you open a lot of brackets that shouldn't even be there in the first place. If you put them all in, it says "invalid syntax" because it wants else statements to complete the ternary expressions.
This code is very confusing but addressing the syntax errors:
All of your if lines need to end with :
if 4 in (a) # missing : at the end
should be
if 4 in a:
Every if body starts with ( but isn't closed
(b = a.count('9')
should be
b = a.count('9')
You will be printing variables that you never assigned to, unless every if check is independently true. so I would recommend at least removing all the if checks and making it flat
b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
but I don't think this will produce the correct answer, though it's hard to see what your goal is.
These aren't errors, but you don't need the extra () around input and print. input() also supports taking a string to display
a = input('input a number: ')
# ...
print('the highest number...')
Update for comment explaining that the goal is to rearrange.
The simplest way is using the python sorted and then joining the result back to a single string
a = input('input a number: ')
highest = ''.join(sorted(a, reverse=True))
print('The highest number you can make is', highest)
However, if you want to keep your existing approach with all the variables, you need only replace the ints in your print with str by quoting them, and using sep='' to remove the spaces in between
print("the highest number you can make is ",
'9'*b, '8'*c, '7'*d, '6'*e, '5'*f, '4'*g,
'3'*h, '2'*i, '1'*j, '0'*k,
sep='')
A more imperative, but less repetitive approach would be to build up a result string as you went
a = input('input a number: ')
result = ''
for i in range(10, -1, -1):
count = a.count(str(i))
result += count * str(i)
print("the highest number you can make is", result)
b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
´
print("the highest number you can make is", ´9´*b, ´8´*c, ´7´*d, ´6´*e, ´5´*f, ´4´*g, ´3´*h, ´2´*i, ´1´*j, ´0´*k)
this seems to work fine - thanks for the help everybody but this works for my purposes
I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:
for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
The output looks like:
0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
Instead I'd like it to be:
0 1 2 3 4
| | | | |
1 2 3 4 5
But I can't get how to do it. Thanks for the help.
Try with list concaternation:
x = 5
print (" ".join(str(i) for i in range(x)))
print ('| '*x)
print (" ".join(str(i) for i in range(1,x+1)))
import sys
myRange = range(5)
for i in myRange:
sys.stdout.write(str(i))
print()
for i in myRange:
sys.stdout.write('|')
print()
for i in myRange:
sys.stdout.write(str(i+1))
print()
You need sys.stdout.write to write without \n. And this code will not work if you have range more than 9 (10+ has 2+ chars, so you need special rules for spaces before |).
Just to throw in a fun (but bad, don't do this) answer:
for i in range(5):
print('{}\033[1B\033[1D|\033[1B\033[1D{}\033[2A'.format(i, i+1), end='')
print('\033[2B')
This uses terminal control codes to print column by column rather than row by row. Not useful here but something that's good to know about for when you want to do weirder terminal manipulation.
You can only print one line at a time. So first you'll have to print the line with all the a elements, then the line with all the bars, and finally the line with all the b elements.
This can be made easier by first preparing every line before printing it:
line_1 = ""
line_2 = ""
line_3 = ""
for i in range(5):
line_1 += str(i)
line_2 += "|"
line_3 += str(i+1)
print(line_1)
print(line_2)
print(line_3)
There are of course many ways with the same basic idea. I picked the one that is (IMHO) easiest to understand for a beginner.
I didn't take spacing into account and once you do, it gets beneficial to use lists:
line_1_elements = []
line_2_elements = []
line_3_elements = []
for i in range(5):
line_1_elements.append(str(i))
line_2_elements.append("|")
line_3_elements.append(str(i+1))
print(" ".join(line_1_elements))
print(" ".join(line_2_elements))
print(" ".join(line_3_elements))
Similar to Tim's solution, just using map instead of the genrators, which I think is even more readable in this case:
print(" ".join(map(str, range(i))))
print("| " * i)
print(" ".join(map(str, range(1, i+1))))
or alternatively, less readable and trickier, a heavily zip-based approach:
def multi(obj):
print("\n".join(" ".join(item) for item in obj))
r = range(6)
multi(zip(*("{}|{}".format(a, b) for a, b in zip(r, r[1:]))))
What's your goal here? If, for example, you print up to n>9, your formatting will be messed up because of double digit numbers.
Regardless, I'd do it like this. You only want to iterate once, and this is pretty flexible, so you can easily change your formatting.
lines = ['', '', '']
for i in range (5):
lines[0] += '%d ' % i
lines[1] += '| '
lines[2] += '%d ' % (i+1)
for line in lines:
print line
so i have to create a code in which it reads every third letter and it creates a space in between each letter, my code creates the spaces but it also has a space after the last letter, this is my code:
msg = input("Message? ")
length = len(msg)
for i in range (0, length, 3):
x = msg[i]
print(x, end=" ")
My output was:
Message?
I enter:
cxohawalkldflghemwnsegfaeap
I get back
c h a l l e n g e
when the output isn't meant to have the last " " after the e.
I have read by adding print(" ".join(x)) should give me the output i need but when i put it in it just gives me a error. Please and Thank you
In Python, strings are one kind of data structures called sequences. Sequences support slicing, which is a simple and fancy way of doing things like "from nth", "to nth" and "every nth". The syntax is sequence[from_index:to_index:stride]. One does not even a for loop for doing that.ago
We can get every 3th character easily by omitting from_index and to_index, and have stride of 3:
>>> msg = input("Message? ")
cxohawalkldflghemwnsegfaeap
>>> every_3th = msg[::3]
>>> every_3th
'challenge'
Now, we just need to insert spaces after each letter. separator.join(iterable) will join elements from iterable together in order with the given separator in between. A string is an iterable, whose elements are the individiual characters.
Thus we can do:
>>> answer = ' '.join(every_3th)
>>> answer
'c h a l l e n g e'
For the final code we can omit intermediate variables and have still a quite readable two-liner:
>>> msg = input('Message? ')
>>> print(' '.join(msg[::3]))
Try
>>> print " ".join([msg[i] for i in range(0, len(msg), 3)])
'c h a l l e n g e'
I'm finishing up an assignment for my 1035 computer science lab and the last thing I need to do is arrange inputted numbers in a diagonal line.
I've tried things like:
print (\tnum2)
and like this:
print ('\t'num2)
but I can't figure out how to do it. I've looked through my programming book, but have been unable to find an explanation on how to do it.
strings in python can be concatenated using the + sign. For example
print(' ' + str(a))
will give the following output for a=1
1
Notice the single blank space before 1. The function str(a) returns the integer a in string format. This is because print statement can only print strings, not integers.
Also
print(' ' * i)
prints i blank spaces. If i = 10, then 10 blank spaces will be printed.
So, the solution to the question can be:
a = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
print((' ' * i) + str(a[i]))
Here's a simple example that prints items in a list on a diagonal line:
>>> l = [1,2,3,4,5]
>>> for i in range(len(l)):
... print("\t" * i + str(l[i]))
...
1
2
3
4
5
You can also do it using .format
nome = input("nome:")
a = " "
b = len(nome)
for i in range(b):
print ("{0} {1}".format(a * i, nome[i]))
print ("\n next \n")
c=b
for i in range(b):
print ("{0} {1}".format(a * c, nome[i]))
c = c-1
this give diagonal increasing or decreasing