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.
Related
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).
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True
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)
So I have this piece of code, very basic stuff that I'm working on. I stumbled upon this "slow type" thing, that I like but if I use it instead of all print functions, most of my output is written on one row.
import sys, time
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.02)
print_slow('What\'s your name?')
name = raw_input()
print_slow('My name is ' + name)
if name == 'alex' or name == 'Alex':
print_slow('That\'s a good name')
if name == 'Alexandru' or name == 'alexandru':
print_slow('That\'s a very good name')
You can print a newline character (\n) at the end of each line where you so desire, or add it to the print_slow function.
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,"'"))