How to include % in string formats in Python 2.7? - python

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

Related

What is wrong with my Python syntax: I am trying to use multiple quotation marks plus variables in a string

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"
}

Simple logical syntax termcolor python

I have simple logical problem with my code. I want my console's output is blue so I import termcolor, but this the problem
from termcolor import colored
winner_name = "John"
result = colored((">>",winner_name,"<<"),"blue")
print(result)
when the code executed, the output is
('>>', 'John" , '<<')
I tried some replace funct
results = result.replace( "(" and ")" and "'" , "" )
This work but the output is
(>> , John , <<)
I Want the output is
>> John <<
You're constructing a tuple. You need to make a single string. There are several ways to do so. You could use + directly
">> " + winner_name + " <<"
or, more idiomatically, you can use f-strings.
f">> {winner_name} <<"
It's printing the brackets because you are printing the tuple.
If you are using a newer version of python you can use f strings:
result = colored(f">> {winner_name} <<", "blue")
Otherwise you can do it like this:
result = colored(">>" + winner_name + "<<", "blue")
Use this instead
colored(f">> {winner_name} <<", "blue")
the variable name in curled brackets will be replaced by it's value inside the f string.
If you don't want to use f strings
colored(">>" + winner_name + "<<", "blue")

How to add strings here

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"}
}}

Python write output separated by semi-colon

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)

Python Printing Elements from a dictionary produces error

I created this block of code for usernames which is read using a loop.
users = {
'aeinstein': {
'first':'albert',
'last':'einstein',
'location':'princeton'
},
'mcurie': {
'first':'marie',
'last':'curie',
'location':'paris',
}
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'], user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
print("\tLocation:" + location.title())
Now, if you observe the following line in the for loop
full_name = user_info['first'], user_info['last']
I expect1 this to append the value albert einstein and marie curie, but this produces the error
print("\tFull name:" + full_name.title())
AttributeError: 'tuple' object has no attribute 'title'
but why is my method wrong and the following therefore correct...
full_name = user_info['first'] + " " + user_info['last']
to produce the following result
Username: aeinstein
Full name:Albert Einstein
Location:Princeton
Username: mcurie
Full name:Marie Curie
Location:Paris
1From the comments: so when you do say print("hello", "world") this type of string concatenation works right but not in the example that I have shown?
The expression user_info['first'], user_info['last'] creates a tuple of two elements (in this case the elements are strings). Tuple object does not have the title method but if you concatenate with the plus operator like you do user_info['first'] + " " + user_info['last'], you create a String and not a tuple so you can use the title method
By adding the , operator in user_info['first'], user_info['last'] you are telling Python that you are giving it a tuple of two strings. By using the + operator, you are simply concatenating the two strings into one string.
full_name = user_info['first'], user_info['last']
I expect this to append the value albert einstein and marie curie […]
Your expectation is wrong.
but why is my method wrong and the following therefore correct...
full_name = user_info['first'] + " " + user_info['last']
Because + is the concatenation operator for strings, and , is not.
As replied by several others you need to use
full_name = user_info['first']+" "+ user_info['last']
OR
full_name = "%s %s" %(user_info['first'],user_info['last'])

Categories