Lists and Strings PYTHON - beginner - python

I am having issues with formatting and understand lists and strings when it comes to classes.
So I have this code here:
class User:
def __init__(self,title):
self.tile=tile
self.rank={}
def addCard(self,compID,number):
if compID in self.cards and number > self.cards[compID]:
self.cards[compID]=number
elif compID not in self.cards:
self.cards[compID]=number
def __str__(self):
self.cardList = []
for compID, number in self.cards.items():
final = compID + "-" + str(number)
self.cardList.append(temp)
self.cardList.sort()
return self.tile + ":" + " " + "Card scores:" + str(self.cardList)
so my result looks like this:
OUTPUT 1:
Cpt.Fred: Card scores: ['diamond-22', 'hearts-4', 'spades-3']
Lt.Connor: Card scores: ['diamond-43']
I am trying to make my result look like this:
OUTPUT 2:
Cpt.Fred: Card scores: [ diamond-22, hearts-4, spades-3 ]
Lt.Connor: Card scores: [ diamond-43 ]
The data is not whats important, its how to get rid of the " ' " at the beginning and the end of the results. I think it has something to do with my last def() statement but I have been trying to format it every way with no luck. Can anyone help turn the first output to look like the second output?

Instead of calling str(self.cardList), you should do:
return "%s: Card scores: [%s]" % (self.title, ", ".join(self.cardList))
The problem is that str on a list calls repr (includes quotes) on the list's elements, whereas you just want the str of the elements joined by commas.

You may need to process and print the list manually. Here's one way you could do that.
def printList(cardlist):
printstr = "[" # Start with [.
for card in cardlist:
printstr += card + ", " "card, "
printstr = printstr[:-2] + "]" # Remove the last ", " before adding the last ].

The problem is in "str(self.cardList)". It prints out the list as is, meaning it puts strings into quotations to distinguished them from numbers and other objects.
def list_to_string(some_list):
str = "["
for i in range(len(some_list)):
str += some_list[i]
if i < len(some_list)-1:
str += ", "
str += "]"
return str
this would parse your list into a string without the quotations

Related

Remove extra space before word ends

I need some help removing the extra space before a word/string ends. Does anyone have any ideas?
input:
hello
output I get (two spaces at the end):
' .... . .-.. .-.. --- '
expected output (only one space at the end, but two spaces between letters):
' .... . .-.. .-.. --- '
Here's my code:
MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..'}
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse=" "
for letter in my_msg:
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+=" * "
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
else:
my_msg_Morse+=" "
return my_msg_Morse
You could just do:
my_msg_Morse_list.replace(' ','')
Edited
I was corrected,
If the problem is always two spaces at the maybe you could just trim the string with
my_msg_Morse = my_msg_Morse[:-1]
I would use the split() method on your string to parse out your morse code into an iterable and then iterate over each code, first using strip() and then ignoring empty elements.
You can do this one of two ways:
Keep track of the index of every letter in your iteration using enumerate(). Check if this is the last letter in my_msg. If it is, don't add the second space.
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse=" "
for index, letter in enumerate(my_msg):
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+=" * "
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter] + " "
if index < len(my_msg) - 1:
my_msg_Morse += " "
else:
my_msg_Morse+=" "
return my_msg_Morse
Build a list and then use str.join() to join it with spaces. We'll also have to add one space before and after the result of the join().
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse_list = []
for letter in my_msg:
if letter=" " and letter not in MORSE_CODES:
my_msg_Morse_list.append("*")
elif letter!=" ":
my_msg_Morse_list.append(MORSE_CODES[letter])
else:
my_msg_Morse_list.append(" ")
# Add the leading and trailing space
return " " + " ".join(my_msg_Morse_list) + " "
I'm going to rewrite your function to make the if-else ladder a little more clear. First, I'm going to add a value for a space in the MORSE_CODES dictionary. This eliminates the need to check if letter is a space. Then, I'm going to use the dict.get() function to get the value of the key letter from MORSE_CODES. get() lets us specify a default value to be returned if the given key doesn't exist in the dictionary.
MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..', ' ': ' '}
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse_list = []
for letter in my_msg:
morse_letter = MORSE_CODES.get(letter, "*")
my_msg_Morse_list.append(morse_letter)
# Add the leading and trailing space
return " " + " ".join(my_msg_Morse_list) + " "
When you do all these things, you can write your entire function in one line if you'd like using a generator expression in place of the loop:
def encode_Morse(my_msg):
return " " + " ".join(MORSE_CODES.get(letter, "*") for letter in my_msg.upper()) + " "
For every function, you can check that it gives the expected output by checking that the following code gives True
' .... . .-.. .-.. --- ' == encode_Morse("hello")

Duplicate Values in For Loop

when I print "amount", I am getting duplicate values. Does this have to do with two for loops back to back on my first three lines?
missing_amount:
['102,131.49']
expected results:
102,131.49
actual results:
102,131.49
102,131.49
code:
body_l = []
for link in url:
body = browser.find_element_by_xpath("//[contains(text(), 'Total:')]").text
body_l.append(body)
icl_dollar_amount = re.findall('(?:[\£$\€]{1}[,\d]+.?\d)', body)[0].split('$', 1)[1]
icl_dollar_amount_l.append(icl_dollar_amount)
if not missing_amount:
logging.info("List is empty")
print("List is empty")
count = 0
for amount in missing_amount:
for count, item in enumerate(icl_dollar_amount_l):
if amount == item:
body = body_l[count]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(amount)
logging.info("Missing " + str(amount))
print("Missing " + str(amount))
With AgentJRock code:
when I print(icl_dollar_amount[i]) and missing_amount[i] my if statement never runs only the else runs. But both list have the same values, please see below.
for i in range(len(missing_amount)):
print("Missing Amount : ", missing_amount[i])
print("ICL DOLLAR", icl_dollar_amount_l[i])
if missing_amount[i] == icl_dollar_amount_l[i]:
body = body_l[i]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(missing_amount[i])
logging.info("Missing " + str(missing_amount[i]))
print("Missing " + str(missing_amount[i]))
print(icl_dollar_amount[i]
ICL DOLLAR 2,760,127.58
ICL DOLLAR 325,845.84
print(missing_amount[i])
Missing Amount : 325,845.84
Missing Amount : 2,760,127.58
you do print("Missing " + str(amount)), but also logging.info("Missing " + str(amount)). I don't know what logging.info does, but i assume it prints to stdout. I'd recommend you to remove the print("Missing " + str(amount))
Yes, you are correct, the inner loop is getting your missing_amount twice.
What type/values are in missing amount, icl_dollar_amount_l, and body_l?
Going off missing values is a list of ints
and icl_dollar_amount_l is another list ints
and bod_l is a dictionary
you might be best doing a single for loop to create an index from a range of the length of your lists. From this index in the for loop, you can compare indexes between two lists of shared indices. I think you're trying to share this index with your dict, which should be no problem with the same index we created
also, You have a count variable outside the for loop but have set another instance of count to the enumerate variable.
the outside count needs to be used with a (+=/-+) set to that variable which is equivalent to the enumerate and redundant.
for i in range(len(missing_amount)):
if missing_amount[i] == icl_dollar_amount_l[i]:
body = body_l[i]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(missing_amount[i])
logging.info("Missing " + str(missing_amount[i]))
print("Missing " + str(missing_amount[i]))

Beginner Python - Printing Values in a List

I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.
Objects=["Calculator", "Pencil", "Eraser"]
print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])
Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?
Thanks
You could use join() here:
Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))
This prints:
Hello Calculator, Pencil, Eraser
You can use the string join function, which will take a list and join all the elements up with a specified separator:
", ".join(['a', 'b', 'c']) # gives "a, b, c"
You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):
Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")
Not sure this is the most elegant way but it works:
strTemp = ""
for i in range(len(Objects)):
strTemp += Objects[i] + " "
print ("Hello " + strTemp)
Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.

Python - Split Function - list index out of range

I'm trying to get a substring in a for loop. For that I'm using this:
for peoject in subjects:
peoject_name = peoject.content
print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
I have some projects that don't have any "-" in the sentence. How can I deal with this?
I'm getting this issue:
builtins.IndexError: list index out of range
for peoject in subjects:
try:
peoject_name = peoject.content
print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
except IndexError:
print("this line doesn't have a -")
you could just check if there is a '-' in peoject_name:
for peoject in subjects:
peoject_name = peoject.content
if '-' in peoject_name:
print(peoject_name, " : ", len(peoject_name), " : ",
len(peoject_name.split('-')[1]))
else:
# something else
You have a few options, depending on what you want to do in the case where there is no hyphen.
Either select the last item from the split via [-1], or use a ternary statement to apply alternative logic.
x = 'hello-test'
print(x.split('-')[1]) # test
print(x.split('-')[-1]) # test
y = 'hello'
print(y.split('-')[-1]) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else y) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else '') # [empty string]

Python: turning a tuple from return statement into a string

I've been working on HTTLCS and am having some difficulty finishing up the problem.
Solving a problem was not much of an issue, but I have trouble returning my result as a string rather than the tuple data type.
Here is my code:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains", wordnum, "words, of which" , eWordnum , "(" , percent , "%)" , "contains an 'e'."
print(wordCount(p))
Python outputs ('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.") which is a tuple, not a string.
I know I can just put print at the end of the function and call the function without print() statement, but how do I solve this with a return statement?
It's because you're using commas in your return statement, which Python is interpreting as a tuple. Try using format() instead:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)
>>> wordCount("doodle bugs")
"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
return "Your text contains " + str(wordnum) +
" words, of which " + str(eWordnum) +
" (" + str(percent) + "%)" + " contains an 'e'."
or
return "Your text contains %s words, of which %s (%s%%) contains an 'e'."
% (wordnum, eWordnum, percent)
In the first case, you do a string concatenation and you have to convert wordnum, eWordnum and other variables that are numeric ones, into str (by doing str(variableName)) to allow the concatenation (and for haven't runtime error)
In the second case, you do a string replacement that means that you give some kind of "placeholder" %s (that means string) and you replace them with tuple argument that follows the % symbol
If you return something separate by , you'll return a tuple (as you can see)
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
A for loop might work, though you would have to format the strings to add spaces to them.
for item in tuplename: print item,
Make sure to keep the comma after item, because that prints it on the same line.
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
dummy = "Your text contains {0} words, of which {1} {2} contains an 'e'.".format(wordnum,eWordnum, percent)
return dummy
print(wordCount(p))
try this :
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
using %(variable_name)s as string formatting is often easier to maintain.
how about this
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."
replace the commas with "+", this should work.

Categories

Resources