So I have a list of names
name_list = ["John Smith", "John Wrinkle", "John Wayne", "David John", "David Wrinkle", "David Wayne"]
I want to be able to search, for example, John and
John Smith
John Wrinkle
John Wayne
will display. At the moment my code will display
John Smith
John Wrinkle
John Wayne
David John
What am I doing wrong?
Here is my code
search = input(str("Search: "))
search = search.lower()
matches = [name for name in name_list if search in name]
for i in matches:
if(search == ""):
print("Empty search field")
break
else:
i = i.title()
print(i)
Change your matches to:
matches = [name for name in name_list if name.startswith(search)]
You can also make some changes to your code:
# You can do this in one go
search = input(str("Search: ")).lower()
# Why bother looping if search string wasn't provided.
if not search:
print("Empty search field")
else:
# This can be a generator
for i in (name for name in name_list if name.startswith(search)):
print(i.title())
Related
I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.
movieDirectorRatingList = [
["Munich: The Edge of War", "Christian Schwochow", "4.1"],
["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
["Iron Man", "Jon Favreau", "4.9"]
]
movieSelection = input("What movie would you like to know about?")
if movieSelection in movieDirectorRatingList:
movieLocation = movieDirectorRatingList.count(movieSelection) - 1
print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )
elif movieSelection not in movieDirectorRatingList:
print("Movie not in list")
else:
print("An unexpected error has occured")
I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list. Thank you in advance for any help.
You need to iterate through each list:
for movie in movieDirectorRatingList:
title, director, rating = movie # let's unpack these here
if movieSelection in movie:
print(f"{movieSelection} directed by {director} {rating}" )
break # found the movie
else:
print("Movie selection not found")
I used your code and reformatted it and made this. It does what I believe you want, but slightly simpler.
mdrl = [
["Munich: The Edge of War", "Christian Schwochow", "4.1"],
["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
["Waterloo", "George P. and Sergei Bondarchuk", "4.0"],
["Iron Man", "Jon Favreau", "4.9"]
]
movieChoice = input("Which movie would you like to get data from?: ")
for i in range(len(mdrl)):
if mdrl[i][0] == movieChoice:
print(mdrl[i][0], "Was directed by", mdrl[i][1], "and had a rating of ", mdrl[i][2])
P.S. I changed a piece of data from your "waterloo" data due to their being two directors being in two different sections in the array.
The scenario is like this, I'm checking 2 strings in a list, I have a variable containing a string of first name, and a variable containing a last name. And a list containing only strings of their full names. I tried using "and" so that if the first name and the last name are both true we can say that the full name in the list is indeed true, I want them to compare to the list of it's original full name so that it will give me a Boolean value of True. But I'm having problem because if I change either one, it still gives off a result of True. Is my scenario possible? or if not is there any work-around? Here is the idea of the code this doesn't work I just used this to explain my work, I hope this may help to visualize my question.
first_name = 'John Eric'
last_name = 'Delos Santos'
list = ['Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric']
if last_name and first_name in list:
print(True)
else:
print(False)
I would appreciate your kind response, Thank you!
From your example, it looks like a pattern possibility is there in the list i.e <lastname>, <firstname>. So you can just search this string in the list
Your condition can become
if f"{last_name}, {first_name}" in list:
print(True)
else:
print(False)
If such a pattern isn't consistent, then you can use this to find the result
result = next((True for i in list if first_name in i and last_name in i), False)
print(result)
This will iterate all the names and check for occurrences of first_name and last_name in each individual string. If it succeeds, it will return True, or else it will fallback to False which you can print
I assume that the list is always ordered in the same way, so you can do:
first_name = 'John Eric'
last_name = 'Delos Santos'
YourList = ['Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric']
full_name = last_name + ", " + first_name
if full_name in YourList:
print(True)
else:
print(False)
If not, please let me know!
I am trying to print the following lines :
'My name is John Smith.'
'My name is John Smith, and I live in CHICAGO'
and I live in chicago'
My code below :
name = 'John Smith'
age = 25
location = 'CHICAGO' # change this to lower case when printing
print('My name is %s.')
print('My name is %s, and I live in %s' )
print(f'My name is {name}.')
'and I live in location.lower()
How can I get the results from the top?
#!/usr/bin/env python3
name = 'john smith'
age = 25
location = 'chicago'
print ('My name is %s, and I live in %s. I am %s years old.' % (name, location, str(age)))
Output:
My name is john smith, and I live in chicago. I am 25 years old.
By the way i recommend you to read this article: https://realpython.com/python-string-formatting/
You can use f-strings for all of them. Use the lower() method to convert the location to lowercase.
print(f'My name is {name}')
print(f'My name is {name}, and I live in {location}')
print(f'and I live in {location.lower()}')
i want to read a text file and want to a specific word and then want to append some other word next to it.
For example:
I want to find first name in a file like John and then want to append last name with "John" like John Smith.
Here is the code i have written up till now.
usrinp = input("Enter name: ")
lines = []
with open('names.txt','rt') as in_file:
for line in in_file:
lines.append(line.rstrip('\n'))
for element in lines:
if usrinp in element is not -1:
print(lines[0]+" Smith")
print(element)
Thats what text file looks like:
My name is FirstName
My name is FirstName
My name is FirstName
FirstName is a asp developer
Java developer is FirstName
FirstName is a python developer
Using replace is one way to do it.
Input file (names.txt):
My name is John
My name is John
My name is John
John is a asp developer
Java developer is John
John is a python developer
Script:
name = 'John'
last_name = 'Smith'
with open('names.txt','r') as names_file:
content = names_file.read()
new = content.replace(name, ' '.join([name, last_name]))
with open('new_names.txt','w') as new_names_file:
new_names_file.write(new)
Output file (new_names.txt):
My name is John Smith
My name is John Smith
My name is John Smith
John Smith is a asp developer
Java developer is John Smith
John Smith is a python developer
search_string = 'john'
file_content = open(file_path,'r+')
lines = []
flag = 0
for line in file_content:
line = line.lower()
stripped_line = line
if search_string in line:
flag = 1
stripped_line = line.strip('\n')+' '+'smith \n'
lines.append(stripped_line)
file_content.close()
if(flag == 1):
file_content = open(file_path,'w')
file_content.writelines(lines)
file_content.close()
**OUTPUT**
My name is FirstName
My name is FirstName
My name is FirstName
FirstName is a asp developer
Java developer is john smith
FirstName is a developer
I'm trying to write a code that iterates through a txt file and only gets the lines I want to print them out.
the text file should look like so:
mimi
passwordmimi
mimi johnson
somejob
joji
passwordjoji
jojo
somejob
john
passwordjohn
jonathan
somejob
....
and so on. this text file contains basically a user information (for a log in). I need to make everyone's username print out and their real name (ex: mimi and mimi johnson.) and only those. I don't want the current user's info to print out (in this ex: joji)
here is my code:
username="joji"
file=open("username.txt","r")
x=file.readlines()
x=[item.rstrip('\n') for item in x]
x=iter(x)
for line in x:
if line==username:
next(x,None)
next(x,None)
next(x,None)
else:
print line + " username" ****username should print out. ex:mimi or john
next(x,None)
print line +" real name ****real name should print out. ex: mimi johnson or jonathan
for whatever reason when I run this program and i print out the second **** i put, it prints out the username's twice. (so ex:
mimi username
mimi real name
mimi johnson username
mimi johnson real name
john username
john real name
jonathan username
jonathan real name
....
why is that? it should print out
mimi username
mimi johnson real name
john username
jonathan realname
...
if someone could help me out i'd be really grateful i dont get python.
Im also open to any other suggestions to do this.
EDIT::: i tried making a change with a suggestion this is the outcome:
new block of code:
else:
print line + "username"
line =next(x,None)
print line
this is the new outcome:
mimi username
passmimi real name
mimi johnson username
somejob real name
john username
passjohn real name
jonathan username
somejob real name(***im assuming this one is from john's job)
:/ its not doing what its supposed to
I would recommend using regex to parse this file:
import re
# regex expression to parse the file as you provided it
# you could access the parseddata as a dict using the
# keys "username", "password", "real_name" and "job"
ex = "\n*(?P<username>.+)\n(?P<password>.+)\n(?P<real_name>.+)\n(?P<job>.+)[\n\$]"
with open("usernames.txt", 'r') as users:
matches = re.finditer(ex, users.read())
for match in matches:
user = match.groupdict() # user is a dict
# print username and real name
print(user['username'], "username", user['real_name'], "real name")
Edit: I figured that regex was not really needed here as the format of this file is quite simple. So here is the same thing without using regex.
def parse(usersfile):
# strip line break characters
lines = (line.rstrip('\n') for line in usersfile)
# keys to be used in the dictionnary
keys = ('username', 'password', 'real_name', 'job')
while True:
# build the user dictionnary with the keys above
user = {key: line for key, line in zip(keys, lines)}
# yield user if all the keys are in the dict
if len(user) == len(keys):
yield user
else: # stop the loop
break
with open("usernames.txt", 'r') as usersfile:
for user in parse(usersfile):
# print username and real name
print(user['username'], "username", user['real_name'], "real name")