arcpy calculate string field: Any ideas what how to fix this? - python

Im trying to store a string value obtained from a loop through a tuple into a field called ROW_1
the code goes like this
for creekclass in listOfClassTuples:
(classname, Permanency, creekWidth, score) = creekclass
arcpy.AddMessage(int(score))
bufferDistance = creekWidth*0.5
if crossingType == "INTERSECT":
stringBuffer = ""
else:
stringBuffer = "%s Meters" % str(bufferDistance)
arcpy.AddMessage(str(bufferDistance))
arcpy.MakeFeatureLayer_management(sourceLayer,"JUST_SELECTED", fieldName +" = '"+ classname + "'")
#arcpy.SelectLayerByAttribute_management("JUST_SELECTED","NEW_SELECTION",fieldName+" = '"+ classname + "'")
#arcpy.SelectLayerByAttribute_management("JUST_SELECTED","SUBSET_SELECTION",fieldName2+" = '"+ Permanency + "'")
#arcpy.CopyFeatures_management("JUST_SELECTED", "A:\Temporary\TempLayer1.shp")
arcpy.SelectLayerByLocation_management(targetLayer, crossingType,
"JUST_SELECTED", stringBuffer, "NEW_SELECTION")
## classname = classname.lower()
if outputField1 != "":
arcpy.CalculateField_management(targetLayer, outputField1, classname)
#arcpy.AddMessage(str(classname))
#arcpy.AddMessage(str(outputField1))
arcpy.CalculateField_management(targetLayer, outputField2, int(score) )
arcpy.Delete_management("Just_selected")
arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION")
except:
arcpy.AddMessage("Function failed")
arcpy.AddMessage(arcpy.GetMessages())
the problem appears when the variable classname is equal to "Virtual Flow":
classname = "Virtual Flow"
in the following line taken from the code above
if outputField1 != "":
arcpy.CalculateField_management(targetLayer, outputField1, classname)

From the syntax in the esri help:
CalculateField_management (in_table, field, expression, {expression_type}, {code_block})
The third argument is a SQL Expression. Since you are passing a string that may have a space in it, the expression needs to be surrounded by single quotes ' '.
Something like this should work:
if outputField1 != "":
arcpy.CalculateField_management(targetLayer, outputField1, "".join(("'",classname,"'"))

Related

Could someone help me with this function? Systems always: Incorrect Not quite, format_name('', '') returned Name: , should be

This is my code
def format_name(first_name, last_name):
string = ('Name: ' +last_name+", "+first_name)
if first_name =="":
return ("Name: " + last_name)
elif last_name =="":
return("Name: "+ first_name)
elif first_name == "" and last_name == "":
return ""
else:
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
Name: Hemingway, Ernest
Name: Madonna
Name: Voltaire
Name:
but the system always showed my result "incorrect"
Not quite, format_name('', '') returned Name: , should be .
We don't see any error in your code. But, one thing is notable that is there is an extra space between first_name and last_name.
Try to remove it and check it again.
string = ('Name: ' +last_name+","+first_name
There seems to be just one logical error, and it is solved by thinking how computer process your code from left to right and from up to down. Now if you give empty strings as arguments to your function’s both parameters (first_name, last_name), first it evaluates if the first_name is an empty string “”.
And as we can see the first if conditional turns out to be true, and this provokes the problem, because the first conditional in your function body will execute the if block, meaning that it will return a string starting as (“Name: “ + last_name) WITHOUT evaluating if the last parameter (last_name) is an empty string as well.
So, first you should test the both parameters if for empty strings.
Like so:
def format_name(first_name, last_name):
string = ('Name: ' +last_name+", "+first_name)
if first_name == "" and last_name == "":
return ""
elif first_name =="":
return ("Name: " + last_name)
elif last_name =="":
return("Name: "+ first_name)
else:
return string
def format_name(first_name, last_name):
if first_name != '' and last_name != '':
string = 'Name:'+' ' + last_name, first_name
elif first_name != '' and last_name == '' or first_name == '' and last_name != '':
string = 'Name:'+' ' + first_name + last_name
else:
string = last_name, first_name
return string
I dont know if this is the right explanation but remenber codes is read from top to bottom by writing the first condition with your parameters empty you are telling the interpreter that as soon as this condition is met it has to return an empty string and you accomplish that with "return("")".
The system tells you that is incorrect because the condition says "if both first and last names are empty return an EMPTY STRING" meaning nothing, in your code you still returning "Name: ".
I hope this helps.
def format_name(first_name, last_name):
string = ('Name: ' + last_name + "," + " " + first_name)
if first_name == "" and last_name == "":
return ("")
elif first_name == "":
return ('Name: ' + last_name)
elif last_name == "":
return ('Name: ' + first_name)
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))

Python - (if/else) extra characters?

So I'm doing my homework but I can't seem to figure out how to add "extra" characters to regular statement.
I want this code to say that lname have to consist only from letters and " " or/and "-" symbols and can't start with " ". How can I achieve this? I don't even know what to search for or try. Isn't there some kind of “includes” function built in? I'm getting desperate.
def perenimi2():
global lname
lname = perenimi.get()
if lname.isalpha():
textVar.set("")
nd2 = {"Perenimi": str(lname)}
uusklient.update(nd2)
post2()
else:
textVar.set ("Sisestage korrektne perekonnanimi!")
What I mean is how can I make IF statement that MUST include letters and may also include "-" or/and space. I want to make fname to be only letters and "-" or/and space. (This is for a name field which also can't start with space)
I'm sorry if this has been asked before but I haven't been able to find the solution.
-----CODE AFTER USING POSTED ANSWER-----
With the posted answer I found a new problem, it now allows input or entry to be empty which can't be empty.
I translated everything to English.
import string
###FirstName
def firstname1():
global fname
allowed = " -"
cantStart = " "
fname = firstname.get()
if (set(fname) <= set(allowed + string.ascii_letters) and not fname.startswith(cantStart)):
textVar.set("")
familyname2()
elif fname == "":
textVar.set("Insert correct name!")
else:
textVar.set("Insert correct name!")
###FamilyName
def familyname2():
global lname
lname = familyname2.get()
allowed = " -"
cantStart = " "
empty = ""
if (set(lname) <= set(allowed + string.ascii_letters) and not lname.startswith(cantStart)):
textVar.set("")
post2()
elif lname == "":
textVar.set("Insert correct family name!")
else:
textVar.set("Insert correct family name!")
firstname1()
import string
ALLOWED = " -"
CANT_START = " "
if (set(lname) <= set(ALLOWED + string.ascii_letters)
and not lname.startswith(CANT_START)
and lname):
No elif branch (i.e. remove it from your code).
The explanation:
string.ascii_letters is "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
set(lname) is the set of all characters in lname, e. g. if lname == "abba", then set(lname) will be "ab".
The <= operation between two sets means “is a subset of”, i.e. if all elements in the left set exist in the right set, too.
lname is True only for nonempty strings (you may also use lname != "", but using only lname is more Pythonic).
The long expression in the if branch is surrounded with parentheses only for the possibility to split it freely into more lines, i.e. without the necessity to end every non-complete line with the continuation symbol (\). Otherwise, it has to be in the form as
if set(lname) <= set(ALLOWED + string.ascii_letters) \
and not lname.startswith(CANT_START) \
and lname:
(or be written fully only in one, very long line).

String argument error with dictionary commands

I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.

How can I split string into variables?

I need to split the string into variables something like:
string = "Hello: My name is..."
title, separator, my_name_is = string.partition(": ")
But, I need a string with "My name is..." always in variable 'my_name_is' even if in the initial string will be only "My name is...".
I think it could be done something like this:
>>>string = "My name is..."
>>>title, separator, my_name_is = string.partition(": ")
>>>if my_name_is == "":
>>> my_name_is = title
>>>print(my_name_is)
My name is...
but I must have this code in one line and can't use the RE (task for the school)
If it has to be in one line without any imports, then this will do the job quite nicely:
string = "Hello: My name is..."
(title, my_name_is), separator = string.split(': ') if ':' in string else (None, string), ':'
print(title)
print(separator)
print(my_name_is)
# Hello
# :
# My name is...
This works also if the string has no 'title':
string = "My name is..."
(title, my_name_is), separator = string.split(': ') if ':' in string else (None, string), ':'
print(title)
print(separator)
print(my_name_is)
# None
# :
# My name is...
I would never ever do such awful oneliners though.

Putting quotation marks inside a string

def add_div(filename, caption):
test = str(filename)
return ('<div><img src=' + test + '><br><p>' + caption + '</p></div>')
def add_body(image_dict, s, order = None):
'''(dict of {str:list of str}, str, list) -> str
If the third parameter is passed, then the filenames
included in the body should only be those in the list and should be added
in the same order as they are listed in the list. '''
new = ''
s = '<html><head></head>'
while order is None:
for (key, value) in image_dict.items():
new += add_div(str(key), str(value[2]))
return (s + '<body><div id="slideshow">' + new + '</body>'+ '</html>')
The output of add_body function is:
how do I get quotation marks around the word images/skater.jpg ?
this is what the file looks like
You have two separate options:
1) Use double quotes
print("Hey that's pretty cool!")
2) Escape the single quotation mark
print('Hey that\'s pretty cool!')
You can include the quotation marks in the string that you are concatenating like this :
def add_div(filename, caption):
test = str(filename)
return ('<div><img src="' + test + '"><br><p>' + caption + '</p></div>')
Use one type of quotation for the string definition and the other for the included quotes:
>>> "bob said: 'hello'"
"bob said: 'hello'"
>>> "I said 'yo bob, how u doing?' in reply"
"I said 'yo bob, how u doing?' in reply"
So to fix your problem, just change the return statement in the first function to:
return ('<div><img src="' + test + '><br><p>'" + caption + '</p></div>')
Note that as a final thing, the parenthesis in the return statement aren't required as return is a not a function or method.
Good answers, but another method is to escape the single or double quotation mark with \
Example:
# this is the same as
# s = "'"
s = '\''
print(s)
#this is the same as
# s = '"'
s = "\""
print(s)

Categories

Resources