0

we have a list with arabic words for exmple

list[0]="هذه"
list[1]="هذا"
list[2]="ذلک"

and we need write each item of that list to a text file in index order and separate them by | character example of written file is

list[0]|list[1]|list[2]

and in example of question output must be

The first word to be written in the file : هذه

The second word to be written in the file :هذا

And the third word to be written in the file :ذلک

but output of file is similar below

هذه|هذا|ذلک

the هذه word must be first and ذلک must be last but it is reverse

the code is

tf = open("temp file.txt", "w",encoding="utf8")
tf.write("هذه")
tf.write('|')
tf.write("هذا")
tf.write('|')
tf.write("ذلک")
tf.write('|')

how can i fix it ?

  • 1
    Your code in the first snippet is not the same as the last. – quamrana Apr 17 '22 at 20:01
  • 1
    Your list is in the opposite order that you say. The `"هذه"` string is at index 2. – ddejohn Apr 17 '22 at 20:01
  • The answer is not as simple as the other comments say. I tried to answer this question, but the mix of left-to-right and right-to-left characters in the text box below seems to make that impossible. The list in your code is in the opposite order from the list in your snippet. If these were straight left-to-right strings, you'd just reverse the items in the list, but given what I just saw, that may be a side effect of the editor you're using. In the short term, do `list.reverse()`. – Tim Roberts Apr 17 '22 at 20:01
  • @quamrana and ddejohn -- I suggest you try to create an answer and fix the order of the strings. I found it impossible to do. – Tim Roberts Apr 17 '22 at 20:04
  • I see. The effect I get is that when I paste the third snippet into a python IDE the order of the strings in the list changes, plus the contents of the file written matches the order required by the OP. – quamrana Apr 17 '22 at 20:17
  • Even writing in the editor does not keep the order, however I edited the text of the question – Mostafa Heydar Apr 17 '22 at 20:20
  • Does this answer your question? https://stackoverflow.com/questions/41243215/how-to-print-arabic-text-correctly-in-python – ddejohn Apr 17 '22 at 20:21
  • I provided an answer below based on my understanding of the question. I think I constructed the original list correctly based on the information provided. – Carl_M Apr 17 '22 at 20:46

1 Answers1

0

The question said use index order, but the original code used literals.

# Build the original list

list = [1,2,3]
list[0]="هذه"
list[1]="هذا"
list[2]="ذلک"
print(f'Original list = {list}')
# Process the list
tf = open("temp file.txt", "w",encoding="utf8")
tf.write(list[2]) # use index not literals
tf.write('|')
tf.write(list[1])
tf.write('|')
tf.write(list[0])
tf.write('|')
tf.close()
result =open("temp file.txt",encoding="utf8")
print(f'{result.read()=}')
result.close()

Output

Original list = ['هذه', 'هذا', 'ذلک']
result.read()='ذلک|هذا|هذه|'
Carl_M
  • 861
  • 1
  • 7
  • 14