讓我們以一個示例檔案作為
11 22 33 44
55 66 77 88
99 00 12 13
我想將其反轉為
13 12 00 99
88 77 66 55
44 33 22 11
uj5u.com熱心網友回復:
如果您將檔案的內容作為字串,則可以使用標準方法來反轉字串 stringVariable[::-1]
uj5u.com熱心網友回復:
def reverse_str(file_to_format_path:str) -> str:
# open the file and get the text to be reversed
with open(file_to_format_path, "r") as str_to_rev:
read_str = str_to_rev.read()
# replace the carriage return with something not expected to be in the text
# change this if for any reason you may have a `??` in your text file
read_str = read_str.replace("\n\n", " ?? ")
# convert this string object to a list
read_str = read_str.split(" ")
# take advantage of the list inbuilt reverse method for this
read_str.reverse()
# now join back the reversed list
read_str =" ".join(read_str)
# replace the newline characters back as required
read_str = read_str.replace( " ?? ", "\n\n")
# returns the reversed string as required
return read_str
reversed_version = reverse_str("example.txt")
output:
before:
11 22 33 44
55 66 77 88
99 00 12 13
after:
13 12 00 99
88 77 66 55
44 33 22 11
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/388581.html
上一篇:洗掉檔案中的重復條目-優化性能
下一篇:創建搜索結果陣列
