I have values stored in variables which i am trying to append in payload but it's not taking,please let me know how to do it
r=(issues["fields"]["resolution"]["name"])
#print (r)
p=(issues["fields"]["customfield_13709"])
#print (p)
s=(issues["fields"]["summary"])
#print(s)
k=(issues["key"])
#print(k)
a=(issues["fields"]["assignee"]["name"])
#print (a)
payload = "{\r\n\t\"fields\":{\r\n\"project\":{\"key\":\"SSETOPS\"},\r\n\"summary\":\"s\",\r\n\"description\":\"k+s\",\r\n\"issuetype\":{\"name\":\"Task\"},\r\n\"customfield_12610\":{\"value\":\"High\"},\r\n\"components\":[{\"name\":\"Other\"}],\r\n\"assignee\":{\"name\":\"rahsingh\"}\r\n}}"
Issue with your code is that you have s and s+k inside the quotes and the interpreter treats it like a normal string not a variable. if you want to append 2 strings you need to use + operation.
strA = "this is string A"
strB = "this is a string B + String A i,e " +strA
print(strB)
output
'this is a string B + String A i,e this is string A'
Here is how to append string to another string in your case:
s = "some summary" #Assumed some Values
k = "something else"
payload = "{\r\n\t\"fields\":{\r\n\"project\":{\"key\":\"SSETOPS\"},\r\n\"summary\":" +'\"'+ s +'\"'+ ",\r\n\"description\":" +'\"'+ k+" "+s +'\"'+ ",\r\n\"issuetype\":{\"name\":\"Task\"},\r\n\"customfield_12610\":{\"value\":\"High\"},\r\n\"components\":[{\"name\":\"Other\"}],\r\n\"assignee\":{\"name\":\"rahsingh\"}\r\n}}"
print(payload)
This is what i got as an output :
{
"fields":{
"project":{"key":"SSETOPS"},
"summary":"some summary",
"description":"something else some summary",
"issuetype":{"name":"Task"},
"customfield_12610":{"value":"High"},
"components":[{"name":"Other"}],
"assignee":{"name":"rahsingh"}
}}
Related
I am trying to use Python to write to a file. However, the code has multiple " in it plus calls a variable. I simply cannot manage the syntax.
The code should result in:
{
"Name of site": "https://.google.com",
Where the website is a variable not a string.
The code attempt is below. It never resolves the variable and just displays it as a string called host_name. I have attempted to add backslashes and quotations (various types of single and double) but whatever I try does not work.
with open ("new_file.txt", "a") as f:
f.write ("{ \n")
f.write("\"Name of site\": \"https://" + host_name + ", \n")
The new_file.txt shows:
"Name of site": "https:// + host_name + "\," + "
I have no idea where the "\," comes from.
You can use f strings, and take advantage of the fact that both '' and "" create string literals.
>>> host_name = example.com
>>> output = "{\n"+ f'"Name of site": "https://{host_name}",' + "\n"
>>> print(output)
{
"Name of site": "https://example.com",
Note that in that example you have to also concatenate strings in order to avoid the fact that f-strings don't allow either braces or backslashes; however, there is even a way around that.
newline = '\n'
l_curly = "{"
output = f'{l_curly}{newline}"Name of site": "https://{host_name}", {newline}'
So that's how you'd build the string directly. But it does also seem more likely that what you really want to is to construct a dictionary, then write that dictionary out using JSON.
>>> import json
>>> host_name = 'example.com'
>>> data = {"Name of site": f"https://{host_name}"}
>>> output = json.dumps(data, indent=4)
>>> print(output)
{
"Name of site": "https://example.com"
}
I have created a inputjson variable and then replacing "'" to '\a"' and creating a dictionary and assigning to json key but the output of newjson variable and dictionary key value is different. In dictionary output / is replaced by //. Can anyone help me with the reason behind this issue.
inputjson = {"project_path": "Store_Execution_Analytics/DSCI/Tech","project_path_pqm": "Store_Execution_Analytics/DSCI/Tech/","project_path_powerbi": "Store_Execution_Analytics/DSCI/Tech","input_db_name": "rtm_storeexecution_pqm"}
print("The existing json value is: " + str(inputjson))
newjson = str(inputjson).replace(r"'", r'\a"')
print("The new json value is: " + str(newjson))
dict1={}
dict1['json'] = newjson
print(dict1)
inputjson = {'gen': 'UAT', 'gen2': 'eu', 'json': '{"project_path": "Store_Execution_Analytics/DSCI/Tech","project_path_pqm": "Store_Execution_Analytics/DSCI/Tech/"}'}
How can I acheive below output in python?
output = {'gen': 'UAT', 'gen2': 'eu', 'json': '{\a"project_path\a": \a"Store_Execution_Analytics/DSCI/Tech\a",\a"project_path_pqm\a": \a"Store_Execution_Analytics/DSCI/Tech/\a"}'}
In python, the \ character is used to escape characters that otherwise have a special meaning, such as newline \n, backslash itself \\, or the quote character \'\". See more at https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals.
Now in the first print (i.e. print("The new json value is: " + str(newjson))), you pass a string to the print function. The print function then displays the string in the console with the escaped characters resolved (a newline char will appear as a true line separator instead of the \n character, etc.).
In the second print (i.e. print(dict1)), the concerned string is a key in the dictionary dict1. Printing a dictionary does not resolve escape characters as it prints the representation of its keys and values. This is why you see the \\ escaped.
This happens because you're putting the string into a dictionary and then printing the entire dictionary. In order for python to represent the dictionary value correctly it has to escape the \a's. You'll see though if you print the value specifically associated with the json key in dict1 it prints as expected.
inputjson = {"project_path": "Store_Execution_Analytics/DSCI/Tech","project_path_pqm": "Store_Execution_Analytics/DSCI/Tech/","project_path_powerbi": "Store_Execution_Analytics/DSCI/Tech","input_db_name": "rtm_storeexecution_pqm"}
print("The existing json value is: " + str(inputjson))
newjson = str(inputjson).replace(r"'", r'\a"')
print("The new json value is: " + str(newjson))
dict1={}
dict1['json'] = newjson
print(dict1['json']) // this prints as expected
Here's an example of this working. https://www.mycompiler.io/view/GmTFEYm
You need to do the replacement for the inputjson["json"], not for the whole dictionary, if you are interested only in "json" field.
inputjson = {'gen': 'UAT', 'gen2': 'eu', 'json': '{"project_path": "Store_Execution_Analytics/DSCI/Tech","project_path_pqm": "Store_Execution_Analytics/DSCI/Tech/"}'}
output = inputjson.copy()
output["json"] = output["json"].replace(r'"', r'\a"')
print(output)
print(output['json'])
# Outputs
## {'gen': 'UAT', 'gen2': 'eu', 'json': '{\\a"project_path\\a": \\a"Store_Execution_Analytics/DSCI/Tech\\a",\\a"project_path_pqm\\a": \\a"Store_Execution_Analytics/DSCI/Tech/\\a"}'}
## {\a"project_path\a": \a"Store_Execution_Analytics/DSCI/Tech\a",\a"project_path_pqm\a": \a"Store_Execution_Analytics/DSCI/Tech/\a"}
I'm new to Python and I'm trying to output fields to a text file. I've been able to throw the output to a text file but it's got "[" and "]" bracketing each row and is separated by commas.
I don't want the enclosing brackets and I have a date field that contains a comma so I need the fields to be separated by semi-colons.
Here's an example of the code that I'm using:
f=open("output.txt","a+")
for item in x['data']:
print "Variable 1: " + str(var1)
print "Variable 2: " + str(var2)
a=str(var1.strip())
b=str(var2.strip())
row = "%s\n" % [a,b]
f.write(row)
My output looks like this:
['var1', 'var2']
I want it to look like this:
'var1'; 'var2'
Any help would be greatly appreciated.
If you want them wrapped in single quotes, 'var1'; 'var2', then use any of
row = "; ".join(repr(x) for x in [a, b])
or
row = "%r; %r" % (a, b)
or
row = "{!r}; {!r}".format(a, b)
I am trying to append % in a string using string formats.
I am trying to get the below output:
a : [" name like '%FTa0213' "]
Try 1 :
a = [ ]
b = {'by_name':"FTa0213"}
a.append(" name like "%" %s' " %b['by_name'])
print "a :",a
Error :
a.append(" name like "%" %s' " %b['by_name'])
TypeError: not all arguments converted during string formatting
Try 2:
a = [ ]
b = {'by_name':"FTa0213"}
c = "%"
a.append(" name like '{0}{1}' ".format(c,b['by_name'])
print "a :",a
Error :
print "a :",a
^
SyntaxError: invalid syntax
How do I include a % in my formatted string?
To include a percent % into a string which will be used for a printf style string format, simply escape the % by including a double percent %%
a = []
b = {'by_name': "FTa0213"}
a.append(" name like %%%s' " % b['by_name'])
print "a :", a
(Docs)
In your first try, the way you use "%" is wrong; the code below could work for your first try.
a.append( "name like %%%s" % b['by_name'])
Since the "%" is special in python string, so you need to add a "%" before the real "%" to escape.
In your second try, there is nothing wrong in your print, you forgot a ")" in your a.append line. ;-)
just put the % there, no need to set the variable
a = [ ]
b = {'by_name':"FTa0213"}
a.append(" name like '%{}' ".format(b['by_name']))
print "a :",a
the output is
a : [" name like '%FTa0213' "]
You can escape the percent sign by doubling it.
a = []
b = {'by_name': "FTa0213"}
a.append(" name like '%%%s' " % b['by_name'])
print "a :", a
output
a : [" name like '%FTa0213' "]
However, I think it's clearer to use the format method:
a = [ ]
b = {'by_name': "FTa0213"}
a.append(" name like '%{by_name}' ".format(**b))
print "a :", a
I want to pass the text that comes from this list to see what is contained in it.
The def used is this:
def getTotal(self) :
total = []
for i in range(self.List.getItemCount()) :
total.append(self.List.getItemText(i))
return total
In my main I have this:
msg+=self.getTotal()
What's the correct way of adding to msg so it'll print correctly to the screen?
Expected output:
['Object1', 'Object2']
I'm assuming you're trying to add the list to a string message. In that case you need to use str() to convert the list into a string:
msg += str(self.getTotal())
You can print the objects in the list by doing:
msg += ', '.join(self.getTotal())
I'm not entirely sure what you expect the output to be but would
output_str = ', '.join(self.getTotal())
assumed the list contains numbers I would do it like this:
print msg + ' ' + str(self.getTotal())
If you want to save the whole content in the message first:
msg += ' ' + str(self.getTotal())
print msg