Create a concatenated string from json object in Python - 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.

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

Python String .strip() function returning wrong output

I have the following string
'file path = data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif'
I am trying to get 256:0:10.0:34:26:-1478_B02_10m.tif from the string above
but if I run
os.path.splitext(filepath.strip('data/imagery/256:0:10.0:34:26:-1478'))[0]
It outputs '_B02_10m'
Same with filepath.rstrip('data/imagery/256:0:10.0:34:26:-1478')
Assuming you want all the string data after the / you can always use string.split. This spits your string into a list of strings split on the split string. Then you would only need the final item of this list.
string_var.split("/")[:-1]
See more official python docs on string.split here.
Python's strip doesn't strip the string in the argument but uses it as a list of characters to remove from the original string see: https://docs.python.org/3/library/stdtypes.html#str.strip
EDIT: This doesn't provide a meaningful solution, see accepted answer.
Instead of using strip you should use string.split()
Following piece of code gets you the required substring:
filepath = "data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif"
print(filepath.split('/')[-1])
Output:
256:0:10.0:34:26:-1478_B02_10m.tif

How can I load a string like this( {u'facebook': {u'identifier': u'http://www.facebook.com/71'}} ) into JSON

I got this string from another python crawler program.
{u'facebook': {u'identifier': u'http://www.facebook.com/71'}}
I have read the most questions about JSON. I know the question is about the single quote mark. but how do I convert it into double quote marks?
I have tried json.dump(), but it only add a pair of double quote marks of the string.
"{u'facebook': {u'identifier': u'http://www.facebook.com/71'}} "
I have also tried to use demjson, but the result is the same as above.
Actually I only need to the string behind the "identifier". How can I get that? Thanks in advance.
Your string "{u'facebook': {u'identifier': u'http://www.facebook.com/71'}} " doesn't look like JSON. First it has single quotes (as you already found out) and it also has unicode prefixes: u.
That string actually looks like valid python, so you can use the ast.literal_eval function to parse it into a dict
from ast import literal_eval
dictionary = literal_eval("{u'facebook': {u'identifier': u'http://www.facebook.com/71'}}"

Python ValueError: expected ':' after format specifier

I'm using a dict in python in an attempt to replace words in a string with whatever is in the dict. When I try to run my code, however, it prints out the error "ValueError: expected ':' after format specifier." I have no idea where this error might be coming from. Does anyone with more pythonic wisdom have any suggestions for me?
Thanks!
Here's an example of my code:
str = """{fruit}"""
dict = {"fruit":"pears"}
str.replace(**dict)
This should make str contain "pears".
UPDATE
I'm purposefully using the triple quoted strings - in my code I'm trying to do a replace with a multiline string,
Also, my code is already using the .format method. I just decided to mix the words when translating it between my code to here. This is an updated version of my example code that isn't working.
my_dict = """{fruit}"""
dict = {"fruit":"pears"}
string.format(**my_dict)
FINAL UPDATE
Thanks for all of the answers I received below. I didn't do a good job of explaining my problem and decided to simplify it which simplified away my problem. I'm doing some meta programming so I was trying to replace within a C function definition and python was trying to use the "{" as a format identifier. I needed to use "{{" to get python to recognize the bracket as a char and not as some beginning to a format identifier.
You want to use the format() function instead of replace():
string = "{fruit}"
my_dict = {"fruit": "pears"}
print(string.format(**my_dict))
Output
pears
A couple of other things: you shouldn't use the Python keywords str and dict as variable names. I have changed your variable names for clarity.
Also, you were using a multi-line string with triple quotes for no particular reason, so I changed that too.
Another simple method to replace sentence with a dictionary. I hope you like the simplicity. Also look into this Single Pass Multiple Replace
import re
s = "node.js ruby python python3 python3.6"
d = {'python': 'python2.7', 'python3': 'python3.5', 'python3.6': 'python3.7'}
pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], s)
print result
This will match whole words only.

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