python changing string quotes [duplicate] - python

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("'",'"')

Related

Create a concatenated string from json object in Python

From a json file, I have extracted the following:
[u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']
But, what I need is to create a string like this (this will be part of a SQL statement)
str = """not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')"""
I am new to this. Do you have any clues for me?
This will be done in Python.
Thank you in advance!
str.join wrapped in a str.format does the job. First & last quotes and parenthesis are handled by format, whereas middle quotes & commas are handled by str.join
s = [u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']
print("not in ('{}')".format("','".join(s)))
result:
not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')
note that str(tuple(s)) generates the same single quoted string, but I don't like relying on the representation of python objects.

A simple python confusion about format string

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.

replace some special character with newline \n

I have a text file with numbers and symbols, i want to delete some character of them and to put new line.
for example the text file is like that:
00004430474314-3","100004430474314-3","1779803519-3","100003004929477-3","100006224433874-3","1512754498-3","100003323786067
i want the output to be like that:
00004430474314
100004430474314
100003004929477
1779803519
100006224433874
1512754498
100003323786067
i tred to replace -3"," with \n by this code but it does not work. any help?
import re
import collections
s = re.findall('\w+', open('text.txt').read().lower())
print(s.replace("-3","",">\n"))
The re.findall is useless here.
with open('path/to/file') as infile:
contents = infile.read()
contents = contents.replace('-3","', '\n')
print(contents)
Another problem with your code is that you seem to think that "-3","" is a string containing -3",". This is not the case. Python sees a second " and interprets that as the end of the string. You have a comma right afterward, which makes python consider the second bit as the second parameter to s.replace().
What you really want to do is to tell python that those double quotes are part of the string. You can do this by manually escaping them as follows:
some_string_with_double_quotes = "this is a \"double quote\" within a string"
You can also accomplish the same thing by defining the string with single quotes:
some_string_with_double_quotes = 'this is a "double quote" within a string'
Both types of quotes are equivalent in python and can be used to define strings. This may be weird to you if you come from a language like C++, where single quotes are used for characters, and double quotes are used for strings.
First I think that the s object is not a string but a list and if you try to make is a string (s=''.join(s) for example) you are going to end with something like this:
0000443047431431000044304743143177980351931000030049294773100006224433874315127544983100003323786067
Where replace() is useless.
I would change your code to the following (tested in python 3.2)
lines = [line.strip() for line in open('text.txt')]
line=''.join(lines)
cl=line.replace("-3\",\"","\n")
print(cl)

Print raw string from variable? (not getting the answers)

I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I can do:
print(r'C:\\Windows\Users\alexb\')
But I cant put an r in front of a variable.... for instance:
test = 'C:\\Windows\Users\alexb\'
print(rtest)
Clearly would just try to print rtest.
I also know there's
test = 'C:\\Windows\Users\alexb\'
print(repr(test))
But this returns 'C:\\Windows\\Users\x07lexb'
as does
test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))
So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just
print(raw(test))
But its not
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
try this. Based on what type of output you want. sometime you may not need single quote around printed string.
test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'")) # output: qweqwe\n1212as\t121\\2asas
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
test = 'C:\\Windows\Users\alexb\'
rawtest = r'%s' %test
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com.
But when I print it in the interactive mode I get double slash - '\\w'
as #Jimmynoarms said:
The Solution for python 3x:
print(r'%s' % your_variable_pattern_str)
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
You can do it two ways:
>>>print("C:\\Windows\Users\alexb\\")
C:\Windows\Users\alexb\
>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\
Store it in a variable:
test = "C:\\Windows\Users\alexb\\"
Use repr():
>>>print(repr(test))
'C:\\Windows\Users\alexb\\'
or string replacement with %r
print("%r" %test)
'C:\\Windows\Users\alexb\\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
To turn a variable to raw str, just use
rf"{var}"
r is raw and f is f-str; put them together and boom it works.
Replace back-slash with forward-slash using one of the below:
re.sub(r"\", "/", x)
re.sub(r"\", "/", x)
This does the trick
>>> repr(string)[1:-1]
Here is the proof
>>> repr("\n")[1:-1] == r"\n"
True
And it can be easily extrapolated into a function if need be
>>> raw = lambda string: repr(string)[1:-1]
>>> raw("\n")
'\\n'
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
Here is a straightforward solution.
address = 'C:\Windows\Users\local'
directory ="r'"+ address +"'"
print(directory)
"r'C:\\Windows\\Users\\local'"

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