How to print list by using format function - python

I transfer form JAVA and pretty new in python.I knew python is a convenience language. Then I consider if or not a way I could use in print(''.format()) function to print a list, which I insert couple of word in between value.
I have already tried print(''.format(for i in list)) as simple example showed below:
movies.append(1)
movies.append('The Shawshank Redemption')
movies.append('5 star')
movies.append('whatever')
movies.append('www.google.com')
print('''
The NO.{} Movie is :{}
Rating:{}
Quote:{}
Link:{}
'''.formate(for i in movie)
of course, it shows error invalid syntax at last statement.

for i in movies is a for statement, so it expects to have a block of code.
What you want is to get every item for item in movies, and then pass each item to the function, so you should do this instead
print('''
The NO.{} Movie is :{}
Rating:{}
Quote:{}
Link:{}
'''.format(*(i for i in movie)) # '*' unpacks the generator, so instead of passing a whole object to the function, you pass every object in the generator as an argument
Note that you can actually pass the unpacked list to format like so
print('''
The NO.{} Movie is :{}
Rating:{}
Quote:{}
Link:{}
'''.format(*movies) # '*' unpacks the generator, so instead of passing a whole object to the function, you pass every object in the generator as an argument

*movies unpack argument lists
movies = []
movies.append(1)
movies.append('The Shawshank Redemption')
movies.append('5 star')
movies.append('whatever')
movies.append('www.google.com')
print('The NO.{}\nMovie is :{}\nRating:{}\nQuote:{}\nLink:{} '.format(*movies))
Output is
The NO.1
Movie is :The Shawshank Redemption
Rating:5 star
Quote:whatever
Link:www.google.com

Related

Use lower() method (or similar) when checking if input is in a list?

I'm working on a project where I have a list of items where some are capitalized (list is currently incomplete because debugging). I need to check if the user's input is in the list, and I'd rather it not be case sensitive. I tried using the lower() method, but it doesn't work for lists. Is there a way to get the same effect as that in the context of this code?
itemList = ['Dirt', 'Oak Log']
def takeName():
itemName = ''
while itemName == '':
itemName = input('What Minecraft item would you like the crafting recipe for?\n')
try:
itemName = int(itemName)
except ValueError:
if itemName.lower() not in itemList.lower():
print('Not a valid Minecraft item name or ID!\n')
itemName = ''
elif itemName.lower() in itemList.lower():
itemName = itemList.lower().index(itemName)
return itemName
You can use list comprehension to convert the list items to lowercase. For example:
itemList_lower = [x.lower() for x in itemList]
Then use itemList_lower in the places in your code where you tried using itemList.lower().
Unfortunately, there is no built-in method that set all the strings of a list to lower case.
If you think about it, it would be inconsistent to develop, because in Python a list can store object of different type, it would be incoherent about the purpose of the data structure itself.
So, you should design and develop an algorithm to do that.
Do not worry though, with "list comprehension" it's quick, simple and elegant, in fact:
lowered_list = [item.lower() for item in itemList]
so now, you have a new list named "lowered_list" that contains all the strings you have stored in the other list, but in lower case.
Cool, isn't it?
You can't use a string function on a list in order to apply this function to all list items. You'll have to apply the function using a list comprehension or using the map function.
Using a list comprehension:
lowerItemList = [item.lower() for item in itemList]
A list comprehension is basiccally a more efficient way and shorter to write short for loops. The above code would be the same as this:
lowerItemList = []
for item in itemList:
itemLower = item.lower()
loserItemList.append(itemLower)
Another way to do this is using the map function. This function applies a function to all items of an iterable.
lowerItemList = list(map(str.lower, itemList))
As this is an a bit more complicated example, here's how it works:
We are using the map function to apply the str.lower function on our item list. Calling str.lower(string) is actually the same as calling string.lower(). Python does this already for you.
So, our result will contain a map object containing all the strings in their lowered form. We need to convert this map object into a list object, as a map object is an iterator and this does not support indexing and many of the list class' methods.
You want a case-insensitive lookup but you want to return a value as it's defined in itemList. Therefore:
itemList = ['Dirt', 'Oak Log']
itemListLower = [e.lower() for e in itemList] # normal form
def takeName():
while True:
itemName = input('What Minecraft item would you like the crafting recipe for? ')
try:
idx = itemListLower.index(itemName.lower()) # do lookup in the normal form
# as the two lists are aligned you can then return the value from the original list using the same index
return itemList[idx]
except ValueError:
print(f'{itemName} is not a valid selection') # user will be promted to re-enter
print(takeName())
Output:
What Minecraft item would you like the crafting recipe for? banana
banana is not a valid selection
What Minecraft item would you like the crafting recipe for? oak log
Oak Log

Calling methods and iterating over list

I'm trying to ask for ingredients in a recipe via the input function. I want to store that ingredient in a dictionary, separated by quantity and ingredient. For example, an input of '3 eggs', should yield {'3': 'eggs'}.
The way i do this is with the separate() and convert_to_dict() methods.
I want to ask continuously for the ingredients by means of the input, hence the while True loop.
Basically, i do this via the following code:
ingredients_list = []
def separate(list):
for i in list:
return re.findall(r'[A-Za-z]+|\d+', i)
def convert_to_dict(list):
i = iter(list)
dct = dict(zip(i, i))
return dct
while True:
ingredient = input("Please input your ingredient: ")
ingredients_list.append(ingredient)
print(convert_to_dict(separate(ingredients_list)))
This works fine, but the only problem with it is that when i input another ingredient, the separate() and convert_to_dict() methods only seem to work for the first ingredient in the ingredient list. For example, i firstly input '3 eggs', and then '100 gr of flour', yet it only returns {'3': 'eggs'}. I'm sure there is something i'm missing, but can't figure out where it goes wrong.
I think you've got the idea of your key-value pairs the wrong way around!
Keys are unique. Updating a dictionary with an existing key will just override your value. So if you have 3 eggs, and 3 cups of sugar, how do you envision your data structure capturing this information?
Rather try doing -
{'eggs': 3} # etc.
That should sort out a lot of problems...
But that's all besides the point of your actual bug. You've got a return in your for-loop in the separate function...This causes the function to return the first value encountered in the loop, and that's it. Once a function's reached a return in exist the function and returns to the outer scope.

How to use append() and make output of loop into new list instead of print

I have a loop I'm using which works great that is:
for i, line in enumerate(lines2):
if "2. Primary Contact Person" in line:
print(*lines[i:i+5], sep="\n")
Which gives me back contact information. So far no issues. But I now want to make the print out and append it into a new list instead of just printing it.
I tried
primary_contact = []
for i, line in enumerate(lines2):
if "2. Primary Contact Person" in line:
primary_contact.append(*lines[i:i+5], sep="\n")
But i get the following error:
TypeError: append() takes no keyword arguments
How would I get this to output to be added into a list?
Using List Comprehension:
primary_contact = ['\n'.join(lines[i:i+5]) for i, line in enumerate(lines2) if "2. Primary Contact Person" in line]
The term:
'\n'.join(lines[i:i+5])
Generates a string equivalent to the earlier output
Python's list.append method takes no additional named arguments. The method append only takes into argument the element which you would like to append to the end of the list. In your case I believe it would be:
primary_contact.append(line)
Depending on what the contents of the actual line looks like, as per your above example - a list slice maybe applicable depending on the actual string you wish to append.

How to fix TypeError: can only concatenate str (not "list") to str

I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere
The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
print("I like the "+cars[0]+" ...")
I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is
TypeError: can only concatenate str (not "list") to str**
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)
use comma , instead of plus +
If you use plus sign + in print ('this is old friend' + new_dinner) statement you will get error.
Your first line actually produces a tuple of lists, hence cars[0] is a list.
If you print cars you'll see that it looks like this:
(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
Get rid of all the square brackets in between and you'll have a single list that you can index into.
This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----) function. But the problem is that you've created 4 lists, you should only have one!
from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', str(new_dinner))
#Try turning the list into a strang only
First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.
cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")
The above code outputs: I like the rav4 ...
You can do like
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', *new_dinner)
Here you are the answer :
cars = (['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
print("I like the "+cars[0][0]+" ...")
What we have done here is calling the list first and then calling the first item in the list.
since you are storing your data in a tuple, this is your solution.

Printing a Table from a Dictionary [duplicate]

This question already has answers here:
Dictionary Help! Extracting values and making a table
(2 answers)
Closed 8 years ago.
Here's the question that I'm supposed to code for:
Write the contract, docstring and implementation for a function showCast that takes a movie title and prints out the characters with corresponding actors/actresses from the given movie in an alphabetical order of characters. The columns must be aligned (20 characters (including the character's name) before the name of the actor/actress.) If the movie is not found, it prints out an error message.
It gives an example of what's supposed to happen here
>>> showCast("Harry Potter and the Sorcerer's Stone")
Character Actor/Actress
----------------------------------------
Albus Dumbledore Richard Harris
Harry Potter Daniel Radcliffe
Hermione Granger Emma Watson
Ron Weasley Rupert Grint
>>> showCast('Hairy Potter')
No such movie found
Here are other functions that I've written for the same project that will probably be of assistance in answering the question. A summary of what I've had to do so far is that I'm creating a dictionary, called myIMDb, with a key of the title of the movie, and the value another dictionary. In that dictionary that key is a character of a movie, and the value is the actor. And I've done stuff with it. myIMDb is a global variable for the record.
Other functions, what they do is the docString
def addMovie (title, charList, actList):
"""The function addMovie takes a title of the movie, a list of characters,
and a list of actors. (The order of characters and actors match one
another.) The function addMovie adds a pair to myIMDb. The key is the title
of the movie while the value is a dictionary that matches characters to
actors"""
dict2 = {}
for i in range (0, len(charList)):
dict2 [charList[i]] = actList[i]
myIMDb[title] = dict2
return myIMDb
I've added three movies,
addMovie("Shutter Island", ["Teddy Daniels", "Chuck Aule"],["Leonardo DiCaprio, ","Mark Ruffalo"])
addMovie("Zombieland", ["Columbus", "Wichita"],["Jesse Eisenberg, ","Emma Stone"])
addMovie("O Brother, Where Art Thou", ["Everett McGill", "Pete Hogwallop"],["George Clooney, ","John Turturro"])
def listMovies():
"""returns a list of titles of all the movies in the global variable myIMDb"""
return (list(myIMDb.keys()))
def findActor(title, name):
""" takes a movie title and a character's name and returns the
actor/actress that played the given character in the given movie. If the
given movie or the given character is notfound, it prints out an error
message"""
if title in myIMDb:
if name in myIMDb[title]:
return myIMDb[title][name]
else:
return "Error: Character not in Movie"
else:
return "Error: No movie found"
Now where I'm having trouble
I'm supposed to write the showCast function, but I'm having a lot of trouble. I've been tinkering with it for a while but when I call myIMDb.values() everything returns. And I can't seem to loop through it to sort them to create the table.
Here's what I've come up with so far, but it doesn't do what I was hoping. I'm just hoping that one of you can steer me in the right direction. (The commented out region is what I was doing before, just so you can see my train of thought. [the print(alist) and print(alist[0]) was just to confirm that it's one big entry in a list, not separated at all])
def showCast(title):
if title in myIMDb:
actList=[]
chList=[]
aList = list(myIMDb.values())
print (aList)
print (aList[0])
""""for i in range (len(aList)):
if i%2==0:
chList.append(aList[i])
else:
actList.append(aList[i])
print(chList)
print(actList)""""
else:
return "Movie not Found"
It's an old question, but I'll take a stab. I think your confusion comes from the nested nature of the myIMDb object. To get back information about a specific movies, you should use the title as a key to myIMDb, e.g. myIMDb[title]. What you get back is another dictionary, that you can then use to get the character/actor key value pairs.
Here's a working version of the showCast function:
def showCast(title):
if title in myIMDb:
print("{0:20} {1:20}".format("Character", r"Actor/Actress"))
print("-"*40)
for character, actor in myIMDb[title].items():
print("{0:20} {1:20}".format(character, actor))
else:
return "Movie not Found"
The first print statement generates the heading, and uses the Python's format string method to get the aligned spacing that you want. The next print statement is the divider, and then the meat of the function is simply iterating over the pairs with a for loop.
I hope that helps.

Categories

Resources