Flask syntax f-string with single quotation mark - python

In a Flask tutorial, https://www.youtube.com/watch?v=cYWiDiIUxQc&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=4
There is a syntax I want to understand
return f"Post('{self.title}', '{self.dateposted}')"
Can someone decompose this line for me?
f string means to return the result of Post() in a string
'{self.title}' is an argument that is a string, because with ''
{} is used to get a variable.
But in the context self.title is ALREADY a string, why use ' '?
Are my explanations correct? And what does ' ' do here?

In the tutorial he returns this value for the __repr__ method of a class.
This method is called when repr() is called on the object. It's also called when you use str() or print() on the class, if a __str__ method has not been implemented for it.
The intention of implementing a __repr__ method is to aid debugging.
If you tried to print the object without defining a __repr__, it would print out like <Post object at 0x00000000>, which doesn't help!
The single-quotes are used for decoration, and they aren't really necessary.
See also: Difference between __str__ and __repr__?
You might also be interested in reading Fluent Python by Luciano Ramalho as it covers these methods and gives great examples of how they might be used (in addition to a lot of other Python wisdom)

I didn't check the link but this just returns a string that would break down to this.
return "Post('" + self.title + "', '" + self.dateposted + "')"
What is done with the returned string I don't know, but I assume it's evaluated somewhere else.
But all an f string does is embed variables or expressions into your string.
If the variable is not a string it converts it to a string first.
To break down your example, in an fstring, anything within the {} gets embedded.
Since the ' are single quotes and outside of the curly braces, they are also part of the string.
Lets say self.title is equal to "My Title" and self.dateposted is equal to "08-22-2020". The returned string would then result in
"Post('My Title', '08-22-2020')"
If you were to then call exec() with this string it would call Post() with 2 positional string arguments.

Related

function argument as an input for f-string to change variables

def cleaning(input):
name = str(input)
read_file = pd.read_csv('#f"{name}".csv')
print(read_file)
cleaning(InputKeyword)
My function must take an input keyword, and this will change the "name" to "#input" word.
I was trying with f-strigs, but it doesn't work. Any ideas or referrals where can I find the solution?
Thanks in advance:)
read_file = pd.read_csv('#f"{name}".csv')
That's not actually an f-string, it's a normal string that has an f, some quotes, and some braces inside it. An f-string must be prefixed with (surprisingly enough) an f :-)
I suggest you try something like:
read_file = pd.read_csv(f"#{name}.csv")
If the name string holds xyzzy, this will try to process the file #xyzzy.csv.
Additionally, it's a very bad idea to use built-in functions as variable names. The input function is one such example. The following (complete) snippet solves both those issues:
# Assumes file_base is a string, see below.
def cleaning(file_base):
read_file = pd.read_csv(f"#{file_base}.csv")
print(read_file)
cleaning("someString")
Note that you can put arbitrary expressions inside f-strings, not just variable names. Hence there's no need to create name as a separate (named) object, you could just insert str(file_base) inside the braces.
However, for your particular case, I don't think the use of str(file_base} is necessary since it appears from tour comments that file_base is already a string, and I believe the formatting for a string without a format_spec is just the string itself(a).
This is why I have f"#{file_base}.csv" in the code above without a str() around the file_base variable.
(a) For objects in general, an {object} snippet inside an f-string will call the object's __format__() method, passing in the format_spec used. Hence f"{something:314159} would use the object method call something.__format__("314159") to format the object into a string.

How to use repr() instead of backquotes in Python 3 [duplicate]

This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 3 years ago.
I'm looking for a way to declare a string that contains double quotes and single quote.
In javascript I would do
let str = `"," '`
But when I try the same syntax in python, my IDE shows this error
Python version 3.7 does not support backquotes, use repr() instead
How can I use repr() to achieve this result?
The reason the error message says what it does is because backquotes have never been used in Python to do what you want. Instead, they used to be a shortcut for using the repr function, that is no longer supported.
According to documentation it take an object
Everything is an object in Python, so there is no issue there. But there is an issue in that the repr function does not do what you want.
We need to go back to the original question instead:
I'm looking for a way to declare a string that contains double quotes and single quote.
In Python, you may either escape whichever quote is the one you used for the string, for example:
"\",\" '" # using double quotes
'"," \'' # using single quotes
Or you may use so-called triple quotes:
""""," '""" # like so
But beware that this does not work if you have the same kind of quote at the end of the string:
# '''"," '''' -- does not work!
'''"," \'''' # works, but it defeats the purpose
In each case, '"," \'' is the form that Python will use to report the string back to you.
The message in the IDE is referring to using backticks around a variable name or other expression. In Python 2, `someVar` was a shortcut for repr(someVar).
But this isn't really what you're trying to do. The message is simply hard-coded for any use of backticks.
You just have to escape the quotes that are the same as the string delimiter.
s = '"," \''
I figured that out
So literally all I had to do was this
text = repr(",'") # returns this string ",'"
The part that confused me was I wasn't sure how to pass the argument to the function since according to documentation I should have passed an object, not a string or a list of string. Until I realized that a string is an object too
A few examples that helped me to understand it in details
>>> print("123")
123
>>> print(repr("123"))
'123'
>>> print(repr(",'"))
",'"

Why does values enclosed in multi line comment work in python

Basically I have a print statement with a value enclosed in a multi line comment block. I am expecting it to be an error but I found out that it actually prints the text enclosed. I am curious as to why it does that.
print '''Test String'''
Python has no multi-line comment syntax. You got confused with one of the Python string literal forms instead.
'''....''' creates a string, just like '...' does. There is a """....""" form as well. The difference is that newlines are permitted in the triple-quoted without requiring escaping:
multi_line_string = '''This is the first line.
But multiple lines are included.
And each newline is included in the value.
'''
You probably thought of these as comments because Python developers prefer this form when creating the documentation string. Python gives special meaning to a string literal used as the first statement in a module, class or function, storing the contents in the object __doc__ attribute.
You don't have to use triple-quoted strings for that, single quotes work too:
>>> def foo():
... 'The foo function'
... return 'bar'
...
>>> foo.__doc__
'The foo function'
The Python style guide recommends you use triple-quoting, always, using double quotes, like this:
def recommended():
"""This is a documentation string.
It follows the style guide by using triple quotes.
"""
See the PEP 257: Docstring Conventions for more information.
Lines enclosed with three quotes are not comments, they are strings. However, python can take them as a comment, the same way this is also a comment
"foo"
#bar
"""foobar"""

Python 2.X adding single quotes around a string

Currently to add single quotes around a string, the best solution I came up with was to make a small wrapper function.
def foo(s1):
return "'" + s1 + "'"
Is there an easier more pythonic way of doing this?
Here's another (perhaps more pythonic) option, using format strings:
def foo(s1):
return "'{}'".format(s1)
What about:
def foo(s1):
return "'%s'" % s1
Just wanted to highlight what #metatoaster said in the comment above, as I missed it at first.
Using repr(string) will add single quotes, then double quotes outside of that, then single quotes outside of that with escaped inner single quotes, then onto other escaping.
Using repr(), as a built-in, is more direct, unless there are other conflicts..
s = 'strOrVar'
print s, repr(s), repr(repr(s)), ' ', repr(repr(repr(s))), repr(repr(repr(repr(s))))
# prints: strOrVar 'strOrVar' "'strOrVar'" '"\'strOrVar\'"' '\'"\\\'strOrVar\\\'"\''
The docs state its basically state repr(), i.e. representation, is the reverse of eval():
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(),.."
Backquotes would be shorter, but are removed in Python 3+.
Interestingly, StackOverflow uses backquotes to specify code spans, instead of highlighting a code block and clicking the code button - it has some interesting behavior though.
This works on Python 3.5+
def foo2(char):
return("'{}'".format(char))

String formatting named parameters?

I know it's a really simple question, but I have no idea how to google it.
how can I do
print '%s' % (my_url)
So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?
just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)
print '%(url)s' % {'url': my_url}
In Python 2.6+ and Python 3, you might choose to use the newer string formatting method.
print('{0}'.format(my_url))
which saves you from repeating the argument, or
print('{url}'.format(url=my_url))
if you want named parameters.
print('{}'.format(my_url, my_url))
which is strictly positional, and only comes with the caveat that format() arguments follow Python rules where unnamed args must come first, followed by named arguments, followed by *args (a sequence like list or tuple) and then *kwargs (a dict keyed with strings if you know what's good for you).
The interpolation points are determined first by substituting the named values at their labels, and then positional from what's left.
So, you can also do this...
print('{}'.format(my_url, my_url, not_my_url=her_url))
But not this...
print('{}'.format(my_url, not_my_url=her_url, my_url))
Solution in Python 3.6+
Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:
print(f'{my_url:s}')
This will evaluate my_url, so if it's not defined you will get a NameError. In fact, instead of my_url, you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s, just like with regular, pre-literal string formatting.
For details on literal string formatting, see PEP 498, where it was first introduced.
You will be addicted to syntax.
Also C# 6.0, EcmaScript developers has also familier this syntax.
In [1]: print '{firstname} {lastname}'.format(firstname='Mehmet', lastname='Ağa')
Mehmet Ağa
In [2]: print '{firstname} {lastname}'.format(**dict(firstname='Mehmet', lastname='Ağa'))
Mehmet Ağa
For building HTML pages, you want to use a templating engine, not simple string interpolation.
Another option is to use format_map:
print('{s}'.format_map({'s': 'my_url'}))
As well as the dictionary way, it may be useful to know the following format:
print '%s' % (my_url, my_url)
Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.
I recommend this syntax
dictionary_of_string_values = {
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
print ('{my_text}'.format(**dictionary_of_string_values))
It is very useful when you have to format a string with lots of placeholders.
You can also make it shorter like this:
print ('{my_text}'.format(
**{
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
)
)

Categories

Resources