Python Forum
File "<string>", line 19, in <module> error is related to what?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File "<string>", line 19, in <module> error is related to what?
#2
My guess is you have a hidden character.
I tried your code from copy and paste and got the same error but, when I typed it in it worked as expected.

class Portfolio:
    def __init__(self):
        self.holdings = {}

    def buy(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) + shares

    def sell(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) - shares

    def __iter__(self):
        return iter(self.holdings.items())


p = Portfolio()
p.buy('Alpha', 15)
p.buy('Beta', 23)
p.buy('Gamma', 9)
p.buy('Gamma', 20)
p.sell('Beta', 5)

str_len = len(max(p)[0])

for (ticker, shares) in p:
    if len(ticker) < str_len:
        spacer = ' '*(str_len - len(ticker) + 2)
    else:
        spacer = ' '*2
    print(f'{ticker} {spacer} {shares}')
Output:
Alpha 15 Beta 18 Gamma 29
Frankduc likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
RE: File "<string>", line 19, in <module> error is related to what? - by menator01 - Jan-26-2022, 04:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  trouble reading string/module from excel as a list popular_dog 0 463 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Need to replace a string with a file (HTML file) tester_V 1 815 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Getting last line of each line occurrence in a file tester_V 1 914 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,457 Sep-27-2022, 01:38 PM
Last Post: buran
  Inserting line feeds and comments into a beautifulsoup string arbiel 1 1,230 Jul-20-2022, 09:05 AM
Last Post: arbiel
  Pandas - error when running Pycharm, but works on cmd line zxcv101 1 1,405 Jun-18-2022, 01:09 PM
Last Post: snippsat
  Print to a New Line when Appending File DaveG 0 1,249 Mar-30-2022, 04:14 AM
Last Post: DaveG
  Find and delete above a certain line in text file cubangt 12 3,657 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,784 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  writelines only writes one line to file gr3yali3n 2 2,453 Dec-05-2021, 10:02 PM
Last Post: gr3yali3n

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020