How to print list value in same line? - python

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)

Related

The count() method counts wrong

Here is my task to solve.
For a list of integers, find and print the items that appear in the list
only once. Items must be printed in the order in which they are
are in the incoming list.
I wrote the code but it also counts two and three digit numbers as a single digits. What's the problem?
x = []
a = input()
a.split(" ")
for i in a:
if a.count(i) == 1:
x.append(i)
print(x)
User Mechanical Pig provides the answer, split does not work in-place, since you're discarding its result what you're looking at is the count of each character in the string, not each space-separated sub-string.
The standard library also contains a collection which is ready-made for this use-case: collections.Counter. You can just give it a sequence of items and it'll collate the counts, which you can then filter:
print([k for k, v in collections.Counter(a.split()).items() if v == 1])
a.split(" ") does not change the value of a, so it is still a string and not a list. Hence when you iterate over a, you only get single characters.
str.split is a method that returns a list, but does not magically turn the string into a list. So you need to assign the value it returns to a variable (for example, to a, if you don't want to hold on to the input string).
You can assign the variable as mentioned above or you can directly use the split function in the loop.
x = []
a = input()
for i in a.split(" "):
if a.count(i) == 1:
x.append(i)
print(x)
or split when you are reading the input.
x = []
a = input().split(" ")
for i in a:
if a.count(i) == 1:
x.append(i)
print(x)
Using the Counter class from the collections module is the right way to do this but here's another way without any imports where you effectively have your own limited implementation of a Counter:
a = '1 2 3 4 4 5 6 7 7 7'
d = {}
for n in a.split():
d[n] = d.get(n, 0) + 1
for k, v in d.items():
if v == 1:
print(k)
Output:
1
2
3
5
6

How to remove last comma from print(string, end=“, ”)

my output from a forloop is
string = ""
for x in something:
#some operation
string = x += string
print(string)
5
66
777
I use the below code to have them on the same line
print(string, end=", ")
and then I get
5, 66, 777,
I want the final result to be
5, 66, 777
How do I change the code print(string, end=", ") so that there is no , at the end
The above string is user input generated it can me just 1 or 2,3, 45, 98798, 45 etc
So far I have tried
print(string[:-1], end=", ") #result = , 6, 77,
print((string, end=", ")[:-1]) #SyntaxError: invalid syntax
print((string, end=", ").replace(", $", "")) #SyntaxError: invalid syntax
print(", ".join([str(x) for x in string])) # way off result 5
6, 6
7, 7, 7
print(string, end=", "[:-1]) #result 5,66,777,(I thought this will work but no change to result)
print(*string, sep=', ') #result 5
6, 6
7, 7, 7
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
user input
twenty five, four, nine
gets
25, 4, 9, #(that stupid comma in the end)
You could build a list of strings in your for loop and print afterword using join:
strings = []
for ...:
# some work to generate string
strings.append(sting)
print(', '.join(strings))
alternatively, if your something has a well-defined length (i.e you can len(something)), you can select the string terminator differently in the end case:
for i, x in enumerate(something):
#some operation to generate string
if i < len(something) - 1:
print(string, end=', ')
else:
print(string)
UPDATE based on real example code:
Taking this piece of your code:
value = input("")
string = ""
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))
print(string, end=", ")
and following the first suggestion above, I get:
value = input("")
string = ""
strings = []
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))
strings.append(string)
print(', '.join(strings))
If you can first construct a list of strings, you can then use sequence unpacking within print and use sep instead of end:
strings = ['5', '66', '777']
print(*strings, sep=', ')
5, 66, 777
In case your for loop is doing also something else than printing, then you can maintain your current structure with this approach.
strings = ['5', '66', '777']
for i in range(len(strings)-1):
# some operation
print(strings[i], end=', ')
# some operation (last time)
print(strings[-1])
5, 66, 777
see I have solved this to print 1 to 5
Previously:
i = 1
while i<=5:
print(i, end=",")
i=i+1
Output:==> 1,2,3,4,5,
Now
lst=[]
i=1
while i<=5:
lst.append(str(i))
i=i+1
print(', '.join(lst))
Output:==> 1,2,3,4,5
I can suggest you to use a if-condition inside a for-loop like below
x=['1','2','3','4','5'] #Driver List
for i in range(0,len(x),1): #This loop iterates through the driver list
if( i==len(x)-1 ): #This checks whether i reached the last positon in iteration
print(i) #If i is in the last position, just print the value of i
else:
print(i,end=" , ") #If i is not in the last position, print the value of i followed by a comma
The output for this code is:
0 , 1 , 2 , 3 , 4 #Notice that no comma is printed in the last position
If text formatting is a concern, the simplest approach is to remove the last comma as shown in this example:
letters = ["a", "b", "c", "d", "e", "f"]
for i in letters:
print(f"{i}".upper(), end=", ") # some text formatting applied
print("\b\b ") # This removes the last comma.
Otherwise,
print (*letters, sep=", ")
works pretty well.
for i in range(10):
if(i==9):
print(i)
else:
print(str(i),end=",")
output : 0,1,2,3,4,5,6,7,8,9
list_name = [5, 10, 15, 20]
new_list = []
[new_list.append(f'({i}*{i+5})') for i in list_name]
print(*new_list,sep="+")
Output: (5*10)+(10*15)+(15*20)+(20*25)
for i in range(1,10):
print(i, end="+")
print("10")
Output:
1+2+3+4+5+6+7+8+9+10
in the end no + sign.

Remove Unwanted Space from Print Function

I need to make a program in Python 3 which outputs the numbers that are not repeted given a sequence of numbers, I have done this so far:
a = list(map(int,input().split()))
for i in a:
if a.count(i) == 1:
print(i,end=" ")
The problem is, if you type the following sequence "4 3 5 2 5 1 3 5", the output will be "4 2 1 " instead of "4 2 1" ( Which was the expected result). My question is, Is there a way to make the "end" argument not to print an extra space at the end?
Thank you,
In that case you better do not let the print(..) add the spaces, but work with str.join instead:
print(' '.join(str(i) for i in a if a.count(i) == 1))
The boldface part is a generator, it yields the str(..) of all the is in a where a.count(i) == 1. We then join these strings together with the space ' ' as separator.
Here print will still add a new line, but we can use end='' to disable that:
print(' '.join(str(i) for i in a if a.count(i) == 1), end='')

(Python 3) avoid printing comma at the end in print(variableName,end=',')

I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')

Is there a better way to accomplish this python excercise? (Beginner)

I'm just starting to learn Python and I'm going through an exercise at the end of a chapter. So far, all I've learned about in the book is the very basics, flow control, functions, and lists.
The exercise is:
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with "and"
inserted before the last item. For example, passing the previous spam list to
the function would return 'apples, bananas, tofu, and cats'. But your function
should be able to work with any list value passed to it.
To solve this, I use the following code (python 3.x.x). I'm wondering if there is a better way to do this. It took a little trial and error, but I fumbled through it until I got this:
myList = ['apples', 'bananas', 'tofu', 'cats']
myList2 = ['apples', 'bananas', 'tofu', 'cats', 'added1', 'added2']
def listFunc(List):
x = 0
for i in List:
x += 1
if x < len(List):
print(i, end=' ')
elif x == len(List):
print('and ' + i)
listFunc(myList2)
Another way to accomplish this would be to use slices and joins:
def listFunc(lst):
if len(lst) == 0: return ''
if len(lst) == 1: return lst[0]
return ", and ".join([", ".join(lst[:-1]), lst[-1]])
Here's a more readable version of the above function using the same core concepts.
def listFunc(lst):
if len(lst) == 0: return '' #no elements? empty string
if len(lst) == 1: return lst[0] #one element? no joining/separating to do, just give it back
firstPart = lst[:-1] #firstPart is now everything except the last element
retFirst = ", ".join(firstPart) #retFirst is now the first elements joined by a comma and a space.
retSecond = ", and " + lst[-1] #retSecond is now ", and [last element]"
return retFirst + retSecond;
The only potentially confusing bits here I think are the slice syntax, negative indices, and string.join
The code lst[:-1] means get everything in lst excepting the last element This is a list slice
The code lst[-1] means get the last element in lst This is negative indexing
And finally, the code ", ".join(firstPart) means get a string containing each element in firstPart separated by a comma and a space
Here is a simple version of the function that doesn't use anything very "fancy" and should be understandable by a beginner. Slicing is probably the most advanced stuff here but should be ok if you went through lists. It also handles two special cases of an empty list and one-item list.
def listFunc(List):
if len(List) == 0: return ''
if len(List) == 1: return List[0]
value = List[0]
for item in List[1:-1]:
value = value + ', ' + item
return value + ', and ' + List[-1]
This is not the way you would normally do it in Python but should be good for learning purposes.
Let's have fun with Python 3 and keep it simple:
def listFunc(myList):
*rest, last = myList
return ", ".join(rest) + (", and " if rest else "") + last
You can make it slightly shorter using enumerate:
def printList():
# x will be the string in the list, y will be an integer
aString = ""
for (y,x) in enumerate(myList):
if y < len(myList) - 1:
aString = aString + x + ", "
else:
aString = aString + "and " + x
.
.
.

Categories

Resources