Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate multi-line string in Python console

In PyCharm, if I open a Python Console, I can't terminate a multi-line string.

Here's what happens in IDLE for comparison:

>>> words = '''one
two
three'''
>>> print(words)
one
two
three
>>>

But if I try the same thing in an interactive Python Console from within PyCharm, the console expects more input after I type the final 3 apostrophes. Anyone know why?

>>> words = '''one
... two
... three'''
...
like image 962
MexTek Avatar asked Nov 11 '22 18:11

MexTek


1 Answers

I'm not sure what the context is, but in many cases it would just be easier to make a tuple/list from the things you want printed on different lines and join them with "\n":

>>> words = "\n".join(["one", "two", "three"])

You may also try three double-quote symbols instead. Maybe PyCharm is confused by what's being delimited. I've always wondered this in Python because strings can be concatenated just by pure juxtaposition. So effectively, '' 'one\n\two\nthree' '' ought to take the three different strings, (1) '' (2) 'one\n\two\nthree' and (3) '', and concatenate them. Since the spaces between them ought not be needed (principle of least astonishment), it's more intuitive to me that the triple-single-(or double)-quote would be interpreted that way. But since the triple version is it's own special character, it doesn't work like that.

In IPython the syntax you give works with no problem. IPython also provides a nice magic command %cpaste in which you can paste multi-line expressions or statements, and then delimit the final line with --, and upon hitting enter, it executes the pasted block. I prefer IPython (running in a buffer in Emacs) to PyCharm by a lot, but maybe you can see if there's a comparable magic function, or just look up the source for that magic function and write one yourself?

like image 81
ely Avatar answered Nov 14 '22 22:11

ely