Terminate multi-line string in Python console - python

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'''
...

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?

Related

Does pep8 allow the usage of \t in a print

Is the usage of escaped characters such as \t allowed by PEP8 in something like print statements?
Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?
Yeah that's fine, it is a fundamental ASCII character - PEP would not deny its use as it may be fundamental to your end result (say an API needed tabs or something) - PEP is all about styling your source code, I wouldn't consider a character in a string to be something that can be decreed by a style guide (PEP8).
Though there is nothing wrong with using \t, you might want to use the textwrap module to allow your indented text to be displayed more naturally in your source code. As an alternative to msg = '\teggs\tmilk\tbread', you can write
import textwrap
def show_list():
msg = """\
eggs
milk
bread"""
print(textwrap.indent(textwrap.dedent(msg), "\t"))
Then show_list() produces the output
eggs
milk
bread
When you indent the definition of msg, the whitespace is part of the literal. dedent removes the common leading whitespace from each line of the string. The indent method then indents each line with, specifically, a tab character.
There is nothing wrong using the tabulator character in a string, at all. See e.g. the Wikipedia link for some common usages. You may be confused by this PEP-8 info:
Use 4 spaces per indentation level.
This is similar to Joe Iddon's answer. It has to be clear that writing a text (not code, of course) is something different than writing code. Texts and their usages are very inhomogeneous. So setting rules how to format your text does not make any sense (if text is not code).
But you also asked "Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?"
Since Python3.6 You can use formatted string literals to get additional spaces (indentation) in your strings you want to print. (If you're using Python3.5 and lower, you can use the str.format instead, for example.)
The usage is like this:
>>> text = "Hello World"
>>> print(f"\t{text}")
Hello World
This is just a toy example, of course. F-Strings become more useful with more complex strings. If you don't have such complex strings, you can consider also using the arguments of print() statement like this, for example:
>>> print("Foo", "Bar", "Foo", "Bar", sep="\t\t") # doubled "\t" only for better displaying
Foo Bar Foo Bar
But often it is simply quite enough to include the tab character in your string, e.g.: "Hello World!\tHow are you doing?\tThat's it.". As already said, don't do that with code (PEP-8), but in texts it is fine.
If you want to use a module for that (it is a built-in module), I recommend using textwrap. See chepner's answer for more information how to use that.

Does escaping work differently in Python shell? (Compared to code in file)

In a Python 3.7 shell I get some unexpected results when escaping strings, see examples below. Got the same results in the Python 2.7 shell.
A quick read in the Python docs seems to say that escaping can be done in strings, but doesn't seem to say it can't be used in the shell. (Or I have missed it).
Can someone explain why escaping doesn't seem to work as expected.
Example one:
input:
>>> "I am 6'2\" tall"
output:
'I am 6\'2" tall'
while >>> print("I am 6'2\" tall")
returns (what I expected):
I am 6'2" tall
(I also wonder how the backslash, in the unexpected result, ends up behind the 6?)
Another example:
input:
>>> "\tI'm tabbed in."
output:
"\tI'm tabbed in."
When inside print() the tab is replaced with a proper tab. (Can't show it, because stackoverflow seems the remove the tab/spaces in front of the line I use inside a code block).
Basically your terminal is calling repr magic method of the string when you enter it in terminal as is. In the same time when you call print over the string it calls __str__ method on it:
s = "I am 6'2\" tall"
s.__repr__()
'\'I am 6\\\'2" tall\''
s.__str__()
'I am 6\'2" tall'
See more on that comparison between those two methods: str vs. repr
and that SO Difference between __str__ and __repr__? question.
Good Lack in your future python adventures.
The interactive shell will give you a representation of the return value of your last command. It gives you that value using the repr() method, which tries to give a valid source code representation of the value; i.e. something you could copy and paste into code as is.
print on the other hand prints the contents of the string to the console, without regards whether it would be valid source code or not.

How to automatically insert spaces to make empty lines in Python files indent?

I recently encountered the common "unexpected indent" problem when trying to evaluate python code by copying them from PyDev and Emacs into a python interpreter.
After trying to fix tab/spaces and some searches, I found the cause in this answer:
This error can also occur when pasting something into the Python
interpreter (terminal/console).
Note that the interpreter interprets an empty line as the end of an
expression, so if you paste in something like
def my_function():
x = 3
y = 7
the interpreter will interpret the empty line before y = 7 as the end
of the expression ...
, which is exactly the case in my situation. And there is also a comment to the answer which points out a solution:
key being that blank lines within the function definition are fine,
but they still must have the initial whitespace since Python
interprets any blank line as the end of the function
But the solution is impractical as I have many empty lines that are problematic for the interpreter. My question is:
Is there a method/tool to automatically insert the right number of initial whitespaces to empty lines so that I can copy-and-paste my code from an editor to an interpreter?
Don't bother with inserting spaces. Tell the interpreter to execute a block of text instead:
>>> exec(r'''
<paste your code>
''')
The r''' ... ''' tripple-quoted string preserves escapes and newlines. Sometimes (though in my experience, rarely) you need to use r""" ... """ instead, when the code block contains tripple-quoted strings using single quotes.
Another option is to switch to using IPython to do your day-to-day testing of pasted code, which handles pasted code with blank lines natively.

pass stryng between two python scripts

I need to pass a string value between two python scripts.
It's not an argument but it's a string containing a sentence (with spaces, commas and so on).
example:
one.py has a string variable "hello world, how are you today?"
and I need to pass it to two.py
How can I achieve this result?
It's not an argument but it's a string containing a sentence (with spaces, commas and so on).
Why isn't that an argument?
I don't know how you were planning to run the other script, but pretty much any way of doing so allows you to pass strings with spaces, commas and so on as arguments.
If you're doing things the smart way, it works automatically:
subprocess.check_call([sys.executable, path_to_script2, arg])
If you're doing something like os.system you'll have to quote the argument manually to pass it through the shell… but the easiest answer there is "don't use os.system, so I won't show how to do that unless you ask for it specifically.
Either way, when script2 runs, its sys.argv[1] will be arg, with the spaces and commas and so on preserved.
If the string is too big, you may run into problems with maximum argv length—and, worse, they may be different problems on different platforms.
Also, if you're using Unicode, especially in Python 2.x, there can be some complexities to deal with.
But, for short-ish all-ASCII strings like "hello world, how are you today?", it's all trivial.
I'd suggest using a text document that one script writes to and the other reads from. It's should be pretty simple to implement.
Documentation for reading and writing files can be found here:
http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

using an alternative string quotation syntax in python

Just wondering...
I find using escape characters too distracting. I'd rather do something like this (console code):
>>> print ^'Let's begin and end with sets of unlikely 2 chars and bingo!'^
Let's begin and end with sets of unlikely 2 chars and bingo!
Note the ' inside the string, and how this syntax would have no issue with it, or whatever else inside for basically all cases. Too bad markdown can't properly colorize it (yet), so I decided to <pre> it.
Sure, the ^ could be any other char, I'm not sure what would look/work better. That sounds good enough to me, tho.
Probably some other language already have a similar solution. And, just maybe, Python already have such a feature and I overlooked it. I hope this is the case.
But if it isn't, would it be too hard to, somehow, change Python's interpreter and be able to select an arbitrary (or even standardized) syntax for notating the strings?
I realize there are many ways to change statements and the whole syntax in general by using pre-compilators, but this is far more specific. And going any of those routes is what I call "too hard". I'm not really needing to do this so, again, I'm just wondering.
Python has this use """ or ''' as the delimiters
print '''Let's begin and end with sets of unlikely 2 chars and bingo'''
How often do you have both of 3' and 3" in a string

Categories

Resources