Home > database >  Printing a list as a string on one line
Printing a list as a string on one line

Time:01-17

So the goal of this code is to print as many permutations as possible from a list of words in a text file. I save all these permutations as a list within a larger list. I am trying to loop through the larger list and print each smaller list as a string.

For example if we have after parsing the input file: [("hi", "bye", "tree"), ("bye", "hi", "tree")]

I want to print this out as:

hibyetree

byehitree

The code I currently have is: click here for code

but this returns:

hi

bye

tree

bye

hi

tree

CodePudding user response:

Just use parameter end of function print()

print(something,end="")

CodePudding user response:

the prints everything in the list,

list = [("hi", "bye", "tree"), ("bye", "hi", "tree")]


for ind, elem in enumerate(list):
    for j in range(len(list[ind])):
        print(elem[j])

result:

hi bye tree bye hi tree

CodePudding user response:

lst = [("hi", "bye", "tree"), ("bye", "hi", "tree")]
print(*(''.join(item) for item in lst), sep='\n')

Explanation

''.join() joins the given items, in your case, the elements of the passed tuples with the empty string '', effectively concatenating them.

*(''.join(item) for item in lst) runs all of this for each item of the outer list. Each item is one of said tuples. The parentheses mean, that this is a generator expression, which is immediately unpacked with the asterisk *. This means that each of the resulting elements will be passed as a positional argument to print().

Each of those items are printed, separated by the string specified by the keyword argument sep, which defaults to ' ', i.e. space. Since you want all of it on a separate line, we use the newline character '\n' instead.

An equivalent functional alternative using the built-in map() would be:

lst = [("hi", "bye", "tree"), ("bye", "hi", "tree")]
print(*map(''.join, lst), sep='\n')
  •  Tags:  
  • Related