So for part of the assignment I am doing, I ask the user their address (including street name) and minus it from 68.
so far I have:
streetName = raw_input("Please enter your address: ")
say the user enters there address as 668 Rickman Street, I am supposed to take the 668 and minus it from 68 and what would be printed is
"your secret code is -600"
-600 being obviously the calculation of 68-668
However I do not know how to take the 668 out of the raw input and put it into the calculation.
You can check and try to cast each splitted string if you are sure you have spaces between your number and street name
streetName = raw_input("Please enter your address: ")
names = streetName.split(' ')
secret_code = -1
for name in names :
try :
secret_code = 68 - int(name)
except ValueError :
continue
# Thanks to Jon Clements
if secret_code > 68 :
print 'something went wrong , check your address'
else
print secret_code
You can go through streetName using a for loop and stop wherever you find the first space, store the index and extract a substring starting in 0 to the index calculated, then parse it to integer.
Example Code:
stringVar = "123 Hello world"
subStringVar = a[0:3]
stringParsed = int(subStringVar)
So now stringParsed is 123, then just do a simple operation 68 - stringParsed.
you can split the input string on whitespace delimiter:
>>> int("668 Rickman Street".split()[0])
668
I think the first thing to do is to understand what data structures you will use
to get to your final answer. Look out for examples on string and list comprehension.
Lets say street_name is a string. If the address occurs in the same index in street_name then you can exit the loop once you have accessed the first word or encountered the first blank space after 686.
Or you can convert the string into a list.
street_name_lst = street_name.split()
where street_name_lst => ['668', 'Rickman', 'Street']
Now you just access the first element using first index.
address = street_name_lst[0]
Now str_address => '686' , but this is in string(incompatible type to do any processing with an Integer type for your case), so lets convert String address
to Integer type.
int_add = int(str_address)
Now you have int_add => 686 and now you can do further computation on it.
Remember data structures and type systems in any language are important.
Also look into PEP8 standard to check for good convention on naming your variables.
https://www.python.org/dev/peps/pep-0008/#id38
It might be helpful to install ipython. check http://ipython.org/
Related
Let's say I have a list of concatenated firstname + lastname combinations like this:
["samsmith","sallyfrank","jamesandrews"]
I also have lists possible_firstnames and possible_lastnames.
If I want to split those full name strings based on values that appear in possible_firstnames and possible_lastnames, what is the best way of doing so?
My initial strategy was to compare characters between full name strings and each possible_firstnames/possible_lastnames value one by one, where I would split the full name string on discovery of a match. However, I realize that I would encounter a problem if, for example, "Sal" was included as a possible first name (my code would try to turn "sallyfrank" into "Sal Lyfrank" etc).
My next step would be to crosscheck what remains in the string after "sal" to values in possible_lastnames before finalizing the split, but this is starting to approach the convoluted and so I am left wondering if there is perhaps a much simpler option that I have been overlooking from the very beginning?
The language that I am working in is Python.
If you are getting similar names, like sam, samantha and saman, put them in reverse order so that the shortest is last
full_names = ["samsmith","sallyfrank","jamesandrews", "samanthasang", "samantorres"]
first_name = ["sally","james", "samantha", "saman", "sam"]
matches = []
for name in full_names:
for first in first_name:
if name.startswith(first):
matches.append(f'{first} {name[len(first):]}')
break
print(*matches, sep='\n')
Result
sam smith
sally frank
james andrews
samantha sang
saman torres
This won't pick out a name like Sam Antony. It would show this as *Saman Tony", in which case, your last name idea would work.
It also won't pick out Sam Anthanei. This could be Samantha Nei, Saman Thanei or Sam Anthanei if all three surnames were in your surname list.
Is this what u wanted
names = ["samsmith","sallyfrank","jamesandrews"]
pos_fname = ["sally","james"]
pos_lname = ["smith","frank"]
matches = []
for i in names:
for n in pos_fname:
if i.startswith(n):
break
else:
continue
for n in pos_lname:
if i.endswith(n):
matches.append(f"{i[:-len(n)].upper()} {n.upper()}")
break
else:
continue
print(matches)
I'm trying to figure out what is probably something very simple. I need to make a program where I print the user's specified city and state that they provide. They need to type it in as city,state in the input statement and their answer is stored in a variable called userInput.
Now, here's my issue: Users won't always have the same city and state. Thus, the index numbers of the string that they need to give will change. My question is: How do I print these two things apart from one another, no matter their position in the string?
Edit: Here is an example of what I am trying to do:
userInput = input("Enter your city and state in the format city,state ")
The program should print "You live in the state of [state the user types]" on one line and "Your city is [city the user types>]" on the other.
If user always input "city,state" with a comma separator you could use split()
user_input = input("Enter city,state :")
city, state = user_input.split(",")
Use the str.split() function to split the user's input at the comma, and use formatted strings to print the values into the lines:
city, state = input("Enter your city and state in the format city,state ").split(',')
print(f"You live in the state of {state}\nYour city is {city}")
Ive written a program which takes in the name and age of multiple entries seperated by a comma and then sepearates the aplhabets from the numerics and then compares the name with a pre defined set/list.
If the entry doesnt match with the pre defined data, the program sends a message"incorrect entry" along with the element which didnt match.
heres the code:
from string import digits
print("enter name and age")
order=input("Seperate entries using a comma ',':")
order1=order.strip()
order2=order1.replace(" ","")
order_sep=order2.split()
removed_digits=str.maketrans('','',digits)
names=order.translate(removed_digits)
print(names)
names1=names.split(',')
names_list=['abby','chris','john','cena']
names_list=set(names_list)
for name in names1:
if name not in names_list:
print(f"{name}:doesnt match with predefined data")
the problem im having is even when i enter chris or john, the program treats them as they dont belong to the pre defined list
sample input : ravi 19,chris 20
output:ravi ,chris
ravi :doesnt match with predefined data
chris :doesnt match with predefined data
also i have another issue , ive written a part to eliminate whitespace but i dont know why, it doesnt elimintae them
sample input:ravi , chris
ravi :doesnt match with predefined data
()chris :doesnt match with predefined data
theres a space where ive put parenthesis.
any suggestion to tackle this problem and/or improve this code is appreciated!
I think some of the parts can be simplified, especially when removing the digits. As long as the input is entered with a space between the name and age, you can use split() twice. First to separate the entries with split(',') and next to separate out the ages with split(). It makes comparisons easier later if you store the names by themselves with no punctuation or whitespace around them. To print the names out from an iterable, you can use the str.join() function. Here is an example:
print("enter name and age")
order = input("Seperate entries using a comma ',': ")
names1 = [x.split()[0] for x in order.split(',')]
print(', '.join(names1))
names_list=['abby', 'chris', 'john', 'cena']
for name in names1:
if name not in names_list:
print(f"{name}:doesnt match with predefined data")
This will give the desired output:
enter name and age
Seperate entries using a comma ',': ravi 19, chris 20
ravi, chris
ravi:doesnt match with predefined data
I am trying to write a program that requests a three-
part name and then displays the middle
name.
Repex:
fullname = str(input('Enter a 3-part name:'))
Roger Dupont Federer
print('Middle name:', fullname[1]
Output: R
However, I want to extract Dupont. What is wrong with my code?
)
Use split():
print(input('Enter a 3-part name:').split(' ')[1])
when you do fullname[1] you're indexing the second character not the second word
I'm trying to execute a bunch of code only if the string I'm searching contains a comma.
Here's an example set of rows that I would need to parse (name is a column header for this tab-delimited file and the column (annoyingly) contains the name, degree, and area of practice:
name
Sam da Man J.D.,CEP
Green Eggs Jr. Ed.M.,CEP
Argle Bargle Sr. MA
Cersei Lannister M.A. Ph.D.
My issue is that some of the rows contain a comma, which is followed by an acronym which represents an "area of practice" for the professional and some do not.
My code relies on the principle that each line contains a comma, and I will now have to modify the code in order to account for lines where there is no comma.
def parse_ieca_gc(s):
########################## HANDLE NAME ELEMENT ###############################
degrees = ['M.A.T.','Ph.D.','MA','J.D.','Ed.M.', 'M.A.', 'M.B.A.', 'Ed.S.', 'M.Div.', 'M.Ed.', 'RN', 'B.S.Ed.', 'M.D.']
degrees_list = []
# separate area of practice from name and degree and bind this to var 'area'
split_area_nmdeg = s['name'].split(',')
area = split_area_nmdeg.pop() # when there is no area of practice and hence no comma, this pops out the name + deg and leaves an empty list, that's why 'print split_area_nmdeg' returns nothing and 'area' returns the name and deg when there's no comma
print 'split area nmdeg'
print area
print split_area_nmdeg
# Split the name and deg by spaces. If there's a deg, it will match with one of elements and will be stored deg list. The deg is removed name_deg list and all that's left is the name.
split_name_deg = re.split('\s',split_area_nmdeg[0])
for word in split_name_deg:
for deg in degrees:
if deg == word:
degrees_list.append(split_name_deg.pop())
name = ' '.join(split_name_deg)
# area of practice
category = area
re.search() and re.match() both do not work, it appears, because they return instances and not a boolean, so what should I use to tell if there's a comma?
The easiest way in python to see if a string contains a character is to use in. For example:
if ',' in s['name']:
if re.match(...) is not None :
instead of looking for boolean use that. Match returns a MatchObject instance on success, and None on failure.
You are already searching for a comma. Just use the results of that search:
split_area_nmdeg = s['name'].split(',')
if len(split_area_nmdeg) > 2:
print "Your old code goes here"
else:
print "Your new code goes here"