-1

Say i have a list formatted something like:a = [a,2,b,3,c,4,d,3] and i want to write to any file that allows to create superscripts, like:

a^2
b^3
c^4

and so forth. What possible ways can this be done (The indices need to be formatted properly, like actual indices)?

u7283
  • 3
  • 1
  • 3
  • I would suggest breaking that list into two parts. Before ^ (`before = [a,b,c]`), and After ^ (`after = [2,3,4]`). Then just using the `csv` library to write each list index element to a line with `^` added between each list's item. (Just a general idea for a start). – semore_1267 Dec 08 '16 at 04:19
  • By default output will be in standard character set. Typically one need to use any reporting library/module if you need formatted output with beautification, different fonts, tables or paragraphs and so on. Subscript and superscript fall in same category. Specific to superscript, please see if this answer helps. http://stackoverflow.com/questions/8651361/how-do-you-print-superscript-in-python – Vijayakumar Udupa Dec 08 '16 at 04:22

3 Answers3

1

As simple as this:

files=open('write.txt','a')
a = ['a','2','b','3','c','4','d','3']
count=0
while count<len(a):
    files.write(a[count]+'^'+a[count+1]+'\n')
    count=count+2 
Ranjana Ghimire
  • 1,785
  • 1
  • 12
  • 20
0

It's basically just opening a file and then joining successive elements with a ^ and then joining all of these with a line-break. Finally this is written to a file and the file is closed:

with open('filename.txt', 'w') as file:
    it = iter(a)
    file.write('\n'.join('^'.join([first, str(second)]) for first, second in zip(it, it)))

If you don't want to use any joins and comprehensions you can also use formatting:

with open('filename.txt', 'w') as file:
    template = '{}^{}\n' * (len(a) // 2)
    formatted = template.format(*a)
    file.write(formatted)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

Here is a simple way to accomplish that. Replace the print statement with your write and you'll be in good shape.

First prep your list by dividing it into 2 pieces:

a =  ['a',2,'b',3,'c',4,'d',3]
first = a[0::2]
second = a[1::2]

Next, loop the first list with enumeration and add the second value:

for i, f in enumerate(first):
    super = '%s^%s' % (f, second[i])
    print(super)  # replace with write function

Output looks like this:

a^2

b^3

c^4

d^3

This should keep it simple!

RandallShanePhD
  • 5,406
  • 2
  • 20
  • 30