Related
How Can i print only value of list in same line ?
My Code is:
t = int(input())
for case_no in range(1, t+1):
n = int(input())
li = list()
for i in range(1, n+1):
if n % i == 0:
li.append(i)
print("Case {}: {}".format(case_no, li, sep=' ', end=''))
My Input Output Sample Result:
2
6
Case 1: [1, 2, 3, 6]
23
Case 2: [1, 23]
My Expected Output:
2
6
Case 1: 1 2 3 6
23
Case 2: 1 23
Try join() to convert your list to string -
" ".join(map(str, li))
Here your list is a list of integers and join() joins every string element of an iterable separated by some string (in this case " "). So, you need to convert each integer to a string first. map() can do that. map() takes a function and apply it on each element of an iterable which is passes as the second arguement (here list li). So, map(str, li) will create an iterable where each element is a string representation of every element of list li
So, your line would be-
print("Case {}: {}".format(case_no, " ".join(map(str, li)), sep=' ', end=''))
You can use generator expression for that too -
print("Case {}: {}".format(case_no, " ".join(str(i) for i in li), sep=' ', end=''))
In this case you are using a generator expression (think of it like list comprehension if you don't know). The generator expresssion iterates over every element of li and returns a stringified (don't know if that's the word) version of that element.
Also, if you just want to print the list and not maintain it for other purposes then you can just simplify it a bit -
t = int(input())
for case_no in range(1, t+1):
n = int(input())
print("Case {}: {}".format(case_no, " ".join(str(i) for i in range(1, n+1) if not n % i), sep=' ', end=''))
You can use print to do it:
data = [[1,2,3,4], [2,4,6]]
for idx,d in enumerate(data,1):
print( f"Case {idx}:", *d) # "splat" the list
prints:
Case 1: 1 2 3 4
Case 2: 2 4 6
Using the splat (*) (or unpacking argument lists) operator to provide all elements of your list as parameters to print:
print( *[1,2,3,4]) == print( 1, 2, 3, 4)
Either you make a string out of the list, either you need another loop to parse the list. There might be other solutions as well.
You can use a comma after the print statement to avoid adding new line.
Making a string :
print("Case {}: {}".format(case_no, "".join(str(li).split(',')).strip('[]'), sep=' ', end=''))
With loop:
print("Case {}: ".format(case_no)),
for i in li:
print(i),
print
You can make elements in list as string li.append(str(i))
And then have join " ".join(li)
A program accepts a number of inputs, for instance numbers or integers, how do you print each and every one of them on a new line.
Eg. I enter this 2,4,5,2,38.
The program should display each one on a new line as this.
Item = input ("Enter your number")
#user enters the following numbers 5,2,6,3,2
#print out each number on a new line
# output
5
2
6
3
2
All saved i one variable.
All you need is a simple for loop that iterates over the input and prints it
data = raw_input('enter ints').split(',')
for n in data:
if n.isdigit():
print n
Note if you are using Pyhon 3.x, you need to use input instead of raw_input
The first row assigns user input data to data variable and splits items by space. (You can change this tow ',' instead)
The for loop does iteration on every item in that list and checks if it is a digit. Because the list elements are strings, we can use isdigit() method of string to test it.
>>> '5'.isdigit()
True
>>> '12398'.isdigit()
True
If you want to do it in another way, maybe using '\n'.join(data) method, which will join the list elements and join them with '\n'.
>>> inpu = raw_input('enter ints\n').split(',')
>>> inpu = [c.strip() for c in inpu]
>>> print '\n'.join(inpu)
1
2
3
4
This is actually the better way to go, as it is simpler than a for loop.
By typing in print() in python it will move to the next line. If it is a list you can do
for num in list:
print(num)
print()
You want to replace "list" with the name of your list.
You can also type in \n in your print function in quotes to move to a new line.
If the numbers are separated by a comma, you can split them by that comma, then join them by a new line:
>>> Item = input ("Enter your numbers: ")
Enter your numbers: 5,2,6,3,2
>>> Result = '\n'.join(Item.split(','))
>>> print(Result)
5
2
6
3
2
>>>
looks like I'm too late to the print party :)
this can work for you too ... wrap it in a function ideally
# assuming STDIN like: "2,4,5,2,38,42 23|26, 24| 31"
split_by = [","," ","|"]
i_n_stdin = input()
for i in split_by:
i_n_stdin = i_n_stdin.split(i)
i_n_stdin = " ".join(i_n_stdin)
#print(i_n_stdin)
for i in i_n_stdin.split():
print(i)
If you want to print a comma-separated list of integers, one integer at each line, you can do:
items = input('Enter a comma-separated list of integers: ')
print(items.replace(",", "\n"))
Example:
Enter a comma-separated list of integers: 1,13,5
1
13
5
You can improve by accepting ";" instead of "," and optional spaces using RegEx:
import re
items = input('Enter a comma-separated list of integers: ')
print(re.sub(r"[,;]\s*", "\n", items))
Example:
Enter a comma-separated list of integers: 2, 4, 5; 2,38
2
4
5
2
38
You can print in the new line by using by defining end parameter as '\n' (for new line) i.e print(x,end='\n')
>>> x=[1,2,3,4]
>>> for i in x:
print(i,end='\n')
output
1
2
3
4
you can use help function in python
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Python 3.x
items = input('Numbers:').split(',') # input returns a string
[print(x) for x in items]
Python 2.x
items = input('Numbers:') # input returns a tuple
# you can not use list comprehension here in python 2,
# cause of print is not a function
for x in items: print x
Just set variable end = '\n'
and print your numbers like:
print(" " + str(num1) + end, str(num2) + end, str(num3) + end)
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
I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.
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