Home > Software design >  Format string output
Format string output

Time:10-19

With this python's code I may read all tickers in the tickers.txt file:

fh = open("tickers.txt") 
tickers_list = fh.read()
print(tickers_list)

The output that I obtain is this:

A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,

Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:

["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]

Any idea? Thanks in advance.

CodePudding user response:

you can to use Split function:

tickers_list = fh.read().split(',')

CodePudding user response:

If you want the output to look in that format you want, you would need to do the following:

tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("[" "".join(['"'   s   '",' for s in tickers_list.split(",")])[:-1] "]")

With the output:

["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]

Code explanation:

['"'   s   '",' for s in tickers_list.split(",")]

Creates a list of strings that contain each individual value, with the brackets as well as the comma.

"".join(...)[:-1]

Joins the list of strings into one string, removing the last character which is the extra comma

"[" .. "]"

adds the closing brackets

Another alternative is to simple use:

print(tickers_list.split(","))

However, the output will be slightly different as in:

['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']

Having ' instead of "

A solution for that however is this:

z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)

Having the correct output, by replacing that character

  • Related