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'])
Related
'''
This is the function that connects 2 nodes from different classes, the nodes exist
'''
def Lives_inRelationship(name,num):
session = graphdb.session()
session.run("MATCH (" + name + ":person {name:'" + name + "'}), ("+num+":Apartment {number:'" + num + "'})"
"MERGE (" + name + ")-[:Lives_in]->(" + num + ")")
Lives_inRelationship("Chandler","19")
'''the exception'''
neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '19': expected "(", "allShortestPaths" or "shortestPath" (line 1, column 45 (offset: 44))
"MATCH (Chandler:person {name:'Chandler'}), (19:Apartment {number:'19'})MERGE (Chandler)-[:Lives_in]->(19)"
^}
Probably the ‘19’ identifier. try to insert an underscore. So ‘_19’ in the MATCH and the MERGE for the rel.
All the label names, relationship names, alias names should not start with number. In your query, we see for Apartment label alias name given as 19. So, it is giving error. Please see below reference for information on naming conventions
https://neo4j.com/docs/developer-manual/current/cypher/syntax/naming/
There are 6 test cases and 5 are getting passed based on python 3 on a string operations problem, but 1 test case is failing since inception.
Pls help me out. The question is as follows:
8 Strings are given in a function.
Remove spaces from both end of strings: first, second, parent, city
Capitalize : first, second, parent
Print Strings with a space : first, second, parent, city
Check if string : 'phone' only contains digits
Check if phone number starts with value in string 'start' and print the result(True or False)
Print : total no. of times 'strfind' appears in the strings : first, second, parent, city
Print : list generated by using split function on 'string1'
Find position of 'strfind' in 'city'
My Code is as follows: Let me know what wrong I have done. 5/6 test cases are passed only 1 test case failed for unknown reason. :(
def resume(first, second, parent, city, phone, start, strfind, string1):
first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isdigit())
print(phone[0]==start[0])
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))
Not too sure without being given details on the test case. However, number 5 may be incorrect as you are only checking if the first values of the strings are the same. This is not the same as checking if "phone number starts with value in string 'start'". I recommend using the following code instead:
print(phone.startswith(start))
In addition number 6 seems like it could cause some mismatches with overlapping strings. Instead I would suggest using:
print(first.count(strfind) + second.count(strfind) + parent.count(strfind) + city.count(strfind))
first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isnumeric())
print(phone.startswith(start))
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))
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 am making an average calculator in python, i have to save the averages in a text file and have done it like this:
Mean = statistics.mean(aver)
Mode = statistics.mode(aver)
Medi = statistics.median(aver)
file = open("Averages.txt", "a")
file.write("\n\nYour numbers are" + aver +
"\nMean : " + Mean +
"\nMode : " + Mode +
"\nMedian : " + Medi)
(aver is a list of numbers i am finding the average of)
when i try to run this part of the code, i recieve the error message:
TypeError: Can't convert 'list' object to str implicitly
I tried basic stuff like adding 'str' on but it doesnt help.
file.write("\n\nYour numbers are" + **aver** +
this would be better as something like this:
aver = " " + ", ".join(aver) + " "
which converts your list to a comma separated string.
So I am defining a function for use in a ArcGIS tool that will verify attributes, catch errors, and obtain user input to rectify those error. I want the tool to select and zoom to the segment that is being currently assessed so that they can make an informed decision. This is what I have been using, and it works well. But the CONVWGID is the variable that will be changing, and I'm not sure how to input that variable into an SQL statement without causing errors.
This is how I had tested the logic:
def selectzoom():
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", " [CONVWGID] = 10000001")
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
Then I needed to work the variable into the function in order to accept different CONVWGID values, which gives me a Runtime/TypeError that I should have known would happen.
Runtime error -
Traceback (most recent call last): - File "string", line 1, in module - TypeError: cannot concatenate 'str' and 'int' objects
def selectzoom(convwkgid):
delimfield = '" [CONVWGID] = ' + convwkgid + ' "'
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", delimfield)
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
And when I alter the delimfield line to change the integer into a string, it selects all of the attributes in the entire feature class. Not just the one that had been passed via the function call.
delimfield = '"[CONVWGID] = ' + str(convwkgid) + '"'
I'm not amazing with SQL and maybe I'm missing something basic with this statement, but I can't figure out why it won't work when I'm basically giving it the same information:
"[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"'
It turned out to be the extra inclusion of Double quotes inside of my single quotes that raised this problem.
Thanks to #Emil Brundage for the help!
Let's say convwkgid = 10000001
'"[CONVWGID] = ' + str(convwkgid) + '"' doesn't equal "[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"' would actually be '"CONVWGID] = 10000001"'
Try instead:
'[CONVWGID] = ' + str(convwkgid)