Reputation: 391
I am trying to implement a function that changes array_1 to array_2, so that array_2 produces the same output as array_1. For example:
for item in array_1:
print(item, end ='')
I want the code below to produce the same output as the code above:
for item in array_2:
print(item)
array_1 = ["Hello", "World", '\n', '\n', "This", "is", '\n', "a", "textarray"]
Running this through the first code gives me:
HelloWorld
Thisis
atextarray
How should I implement the function that changes array_1 to array_2 so that it produces the same output above?
Upvotes: 0
Views: 20103
Reputation: 106455
Since all you're really looking for is to change the default behavior of print
so that it doesn't output a trailing newline by default, you can use functools.partial
to make end=''
a default parameter instead. This way, you don't need to worry about creating a new list from array_1
.
from functools import partial
print = partial(print, end='')
array_1 = ["Hello", "World", '\n', '\n', "This", "is", '\n', "a", "textarray"]
for item in array_1:
print(item)
This outputs:
HelloWorld
Thisis
atextarray
Upvotes: 2
Reputation: 365657
What you want is impossible.
First, notice that the reverse direction would be easy. The difference is that the items in array2
are printed with a newline after each one, while the items in array1
are printed with nothing after each one, so all you'd need to do is add a \n
to the end of each item in array_1
.
array_2 = [item+'\n' for item in array_1]
You can't just reverse that. There's obviously nothing like item-'\n'
. It every item happened to end with a \n
, you could do item[:-1]
, but most of them don't, and you can't remove a newline that isn't there.
And there's no way to cancel out the newline that print
is going to add after the string with an anti-newline
. I mean, you could include a terminal control sequence to move the cursor up one line so it kind of looks like it did the same thing, but it's not actually doing the same thing, and that would be ridiculously easy to break (run the code on Windows, redirect the output to a file, …).
You can get pretty close. You never said that you need the elements to be in one-to-one correspondence, so you can just do this:
array_2 = [''.join(array_1)]
Now you've just got one item in array_2
, so the fact that it's printing newlines between the items doesn't matter.
But there's still a newline at the end, after all one items. And still no way to get rid of that (since the last item doesn't end in a \n
that you can remove).
So, the problem is impossible. (Short of trick-question answers like redefining print
to special-case your output or something.)
Upvotes: 1