A simple python confusion about format string - python

New to python and I am learning this tutorial:
http://learnpythonthehardway.org/book/ex8.html
I just cannot see why the line "But it didn't sing." got printed out with double-quote and all the others got printed with single quote.. Cannot see any difference from the code...

The quotes depends on the string: if there are no quotes, it will use simple quotes:
>>> """no quotes"""
'no quotes'
if there is a single quote, it will use double quotes:
>>> """single quote:'"""
"single quote:'"
if there is a double quote, it will use single quotes:
"""double quote:" """
'double quote:" '
if there are both, it will use single quotes, hence escaping the single one:
>>> """mix quotes:'" """
'mix quotes:\'" '
>>> """mix quotes:"' """
'mix quotes:"\' '
>>> '''mix quotes:"' '''
'mix quotes:"\' '
There won't be a difference though when you print the string:
>>> print '''mix quotes:"' '''
mix quotes:"'
the surroundings quotes are for the representation of the strings:
>>> print str('''mix quotes:"' ''')
mix quotes:"'
>>> print repr('''mix quotes:"' ''')
'mix quotes:"\' '
You might want to check the python tutorial on strings.

The representation of a value should be equivalent to the Python code required to generate it. Since the string "But it didn't sing." contains a single quote, using single quotes to delimit it would create invalid code. Therefore double quotes are used instead.

Python has several rules for outputting the repr of strings.
Normally, it uses ' to surround them, except if there are 's within it - then it uses " for removing the need of quoting.
If a string contains both ' and '"characters, it uses's and quotes the"`.
As there can be several valid and equivalent representations of a string, these rues might change from version to version.
BTW, in the site you linked to the answer is given as well:
Q: Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?
A: Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.

Related

python changing string quotes [duplicate]

I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.
There is no difference between "single quoted" and "double quoted" strings in Python:
both are parsed internally to string objects.
I mean:
a = "European Swallow"
b = 'African Swallow'
Are internally string objects.
However you might mean to add an extra quote inside an string object, so that the content itself show up quoted when printed/exported?
c = "'Unladen Swallow'"
If you have a mix of quotes inside a string like:
a = """ Merry "Christmas"! Happy 'new year'! """
Then you can use the "replace" method to convert then all into one type:
a = a.replace('"', "'")
If you happen to have nested strings, then replace first the existing quotes to escaped quotes, and later the otuer quotes:
a = """This is an example: "containing 'nested' strings" """
a = a.replace("'", "\\\'")
a = a.replace('"', "'")
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:
doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
json.dump(doubleQString ,f)
Notice I'm using dump, not dumps.
Sampledict.json will look like this:
"my normal string"
In my case I needed to print list in json format.
This worked for me:
f'''"inputs" : {str(vec).replace("'", '"')},\n'''
Output:
"inputs" : ["Input_Vector0_0_0", "Input_Vector0_0_1"],
Before without replace:
f'"inputs" : {vec},\n'
"inputs" : ['Input_Vector0_0_0', 'Input_Vector0_0_1'],
The difference is only on input. They are the same.
s = "hi"
t = 'hi'
s == t
True
You can even do:
"hi" == 'hi'
True
Providing both methods is useful because you can for example have your string contain either ' or " directly without escaping.
In Python, there is no difference between strings that are single or double quoted, so I don't know why you would want to do this. However, if you actually mean single quote characters inside a string, then to replace them with double quotes, you would do this: mystring.replace('\'', '"')
Actually, none of the answers above as far as I know answers the question, the question how to convert a single quoted string to a double quoted one, regardless if for python is interchangeable one can be using Python to autogenerate code where is not.
One example can be trying to generate a SQL statement where which quotes are used can be very important, and furthermore a simple replace between double quote and single quote may not be so simple (i.e., you may have double quotes enclosed in single quotes).
print('INSERT INTO xx.xx VALUES' + str(tuple(['a',"b'c",'dfg'])) +';')
Which returns:
INSERT INTO xx.xx VALUES('a', "b'c", 'dfg');
At the moment I do not have a clear answer for this particular question but I thought worth pointing out in case someone knows. (Will come back if I figure it out though)
If you're talking about converting quotes inside a string, One thing you could do is replace single quotes with double quotes in the resulting string and use that. Something like this:
def toDouble(stmt):
return stmt.replace("'",'"')

How to get rid of the single quotes around the representation of a string?

This sample code prints the representation of a line from a file. It allows its contents to be viewed, including control characters like '\n', on a single line—so we refer to it as the "raw" output of the line.
print("%r" % (self.f.readline()))
The output, however, appears with ' characters added to each end which aren't in the file.
'line of content\n'
How to get rid of the single quotes around the output?
(Behavior is the same in both Python 2.7 and 3.6.)
%r takes the repr representation of the string. It escapes newlines and etc. as you want, but also adds quotes. To fix this, strip off the quotes yourself with index slicing.
print("%s" %(repr(self.f.readline())[1:-1]))
If this is all you are printing, you don't need to pass it through a string formatter at all
print(repr(self.f.readline())[1:-1])
This also works:
print("%r" %(self.f.readline())[1:-1])
Although this approach would be overkill, in Python you can subclass most, if not all, of the built-in types, including str. This means you could define your own string class whose representation is whatever you want.
The following illustrates using that ability:
class MyStr(str):
""" Special string subclass to override the default representation method
which puts single quotes around the result.
"""
def __repr__(self):
return super(MyStr, self).__repr__().strip("'")
s1 = 'hello\nworld'
s2 = MyStr('hello\nworld')
print("s1: %r" % s1)
print("s2: %r" % s2)
Output:
s1: 'hello\nworld'
s2: hello\nworld

The last line of this python program uses both " and ' but I don't know why

Ok on this link it shows the last line of output that has ' around everything except the third sentence and I do not know why. This bothered me at the beginning and thought it was just a weird mistake but its on the "extra credit" so now I am even more curious.
This is because the %r formatter prints the argument in the form you may use in source code, which, for strings, means that it is quote-delimited and escaped. For boolean values, this is just True or False. To print the string as it is, use %s instead.
>>> print '%s' % '"Hello, you\'re"'
"Hello, you're"
>>> print '%r' % '"Hello, you\'re"'
'"Hello, you\'re"'
python's repr() function, which is invoked by interpolating the %r formatting directive, has the approximate effect of printing objects the way they would appear in source code.
There are several ways to format strings in python source, using single or double quotes, with backslash escapes or as raw strings, as simple, single line strings or multi line strings (in any combination). Python picks only two ways to format strings, as single or double quoted, single line strings with escapes instead of raw.
Python makes a crude attempt at picking a minimal format, with a slight bias in favor of the single quote version (since that would be one fewer keystrokes on most keyboards).
The rules are very simple. If a string contains a single quote, but no double quotes, python prints the string as it would appear in python source if it were double quoted, Otherwise it uses single quotes.
Some examples to illustrate. Note for simplicity all of the inputs use triple quotes to avoid backslash escapes.
>>> ''' Hello world '''
' Hello world '
>>> ''' "Hello world," he said. '''
' "Hello world," he said. '
>>> ''' You don't say? '''
" You don't say? "
>>> ''' "Can't we all just get along?" '''
' "Can\'t we all just get along?" '
>>>

How to write string literals in Python without having to escape them?

Is there a way to declare a string variable in Python such that everything inside of it is automatically escaped, or has its literal character value?
I'm not asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I don't have to manually go through and escape everything for very large strings.
Raw string literals:
>>> r'abc\dev\t'
'abc\\dev\\t'
If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:
a = r"""This is a multiline string
with more than one line
in the source code."""
There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.
Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.
That is, there's no way to have the string
' ''' """ " \
properly stored in any Python string literal without internal escaping of some sort.
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
(Assuming you are not required to input the string from directly within Python code)
to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;
input_ = '/directory_of_text_file/your_text_file.txt'
input_open = open(input_,'r+')
input_string = input_open.read()
print input_string
This will print the literal text of whatever is in the text file, even if it is;
' ''' """ “ \
Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.
Use print and repr:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> repr(s)
"'\\tgherkin\\n'"
# print(repr(..)) gets literal
>>> print(repr(s))
'\tgherkin\n'
>>> repr('\tgherkin\n')
"'\\tgherkin\\n'"
>>> print('\tgherkin\n')
gherkin
>>> print(repr('\tgherkin\n'))
'\tgherkin\n'

Convert single-quoted string to double-quoted string

I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.
There is no difference between "single quoted" and "double quoted" strings in Python:
both are parsed internally to string objects.
I mean:
a = "European Swallow"
b = 'African Swallow'
Are internally string objects.
However you might mean to add an extra quote inside an string object, so that the content itself show up quoted when printed/exported?
c = "'Unladen Swallow'"
If you have a mix of quotes inside a string like:
a = """ Merry "Christmas"! Happy 'new year'! """
Then you can use the "replace" method to convert then all into one type:
a = a.replace('"', "'")
If you happen to have nested strings, then replace first the existing quotes to escaped quotes, and later the otuer quotes:
a = """This is an example: "containing 'nested' strings" """
a = a.replace("'", "\\\'")
a = a.replace('"', "'")
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:
doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
json.dump(doubleQString ,f)
Notice I'm using dump, not dumps.
Sampledict.json will look like this:
"my normal string"
In my case I needed to print list in json format.
This worked for me:
f'''"inputs" : {str(vec).replace("'", '"')},\n'''
Output:
"inputs" : ["Input_Vector0_0_0", "Input_Vector0_0_1"],
Before without replace:
f'"inputs" : {vec},\n'
"inputs" : ['Input_Vector0_0_0', 'Input_Vector0_0_1'],
The difference is only on input. They are the same.
s = "hi"
t = 'hi'
s == t
True
You can even do:
"hi" == 'hi'
True
Providing both methods is useful because you can for example have your string contain either ' or " directly without escaping.
In Python, there is no difference between strings that are single or double quoted, so I don't know why you would want to do this. However, if you actually mean single quote characters inside a string, then to replace them with double quotes, you would do this: mystring.replace('\'', '"')
Actually, none of the answers above as far as I know answers the question, the question how to convert a single quoted string to a double quoted one, regardless if for python is interchangeable one can be using Python to autogenerate code where is not.
One example can be trying to generate a SQL statement where which quotes are used can be very important, and furthermore a simple replace between double quote and single quote may not be so simple (i.e., you may have double quotes enclosed in single quotes).
print('INSERT INTO xx.xx VALUES' + str(tuple(['a',"b'c",'dfg'])) +';')
Which returns:
INSERT INTO xx.xx VALUES('a', "b'c", 'dfg');
At the moment I do not have a clear answer for this particular question but I thought worth pointing out in case someone knows. (Will come back if I figure it out though)
If you're talking about converting quotes inside a string, One thing you could do is replace single quotes with double quotes in the resulting string and use that. Something like this:
def toDouble(stmt):
return stmt.replace("'",'"')

Categories