-2

These commands:

l = ["1\n2"]    
print(l)

print

['1\n2']

I want to print

['1
2']

Is it possible when we generate the list outside of the print() command?

2
  • 3
    May I ask, what's wrong with this question?
    – DSblizzard
    May 24, 2014 at 17:19
  • I didn't downvote. You can improve the question by stating explicitly what you want, e.g.: I'd like to get the print (repr) output, but string literals should contain a newline character instead of \n. Alternatively you can give more examples.
    – pts
    May 24, 2014 at 17:24

4 Answers 4

2

A first attempt:

l = ["1\n2"]
print(repr(l).replace('\\n', '\n'))

The solution above doesn't work in tricky cases, for example if the string is "1\\n2" it replaces, but it shouldn't. Here is how to fix it:

import re
l = ["1\n2"]
print(re.sub(r'\\n|(\\.)', lambda match: match.group(1) or '\n', repr(l)))
1

Only if you are printing the element itself (or each element) and not the whole list:

>>> a = ['1\n2']
>>> a
['1\n2']
>>> print a
['1\n2']
>>> print a[0]
1
2

When you try to just print the whole list, it prints the string representation of the list. Newlines belong to individual elements so get printed as newlines only when print that element. Otherwise, you will see them as \n.

1
  • This actually does not put the element in a list like format, as shown in the OP's example. May 24, 2014 at 17:19
1

You should probably use this, if you have more than one element

>>> test = ['1\n2', '3', '4\n5']
>>> print '[{0}]'.format(','.join(test))
[1
2,3,4
5]
3
  • Please post the input that you are passing to the above line. May 24, 2014 at 17:23
  • 1
    @DSblizzard - You must be running a pretty old version of Python. Such older versions require that you explicitly number the format fields. Replace '[{}]' with '[{0}]' to fix the problem.
    – user2555451
    May 24, 2014 at 17:24
  • And what Python version are you using? May 24, 2014 at 17:24
0

Try this:

s = ["1\n2"]
print("['{}']".format(s[0]))
=> ['1
   2']
3
  • 1
    Downvoter: care to comment? the input and the output in my answer are exactly as in the question, so what's wrong? May 24, 2014 at 17:15
  • I didnt downvote, but print("['{}']".format(*s)) looks better, no? May 24, 2014 at 17:16
  • @thefourtheye not necessarily, we'd need to see more sample inputs to tell if that would work. May 24, 2014 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.