反转线条和单词
Reversing lines and words
要写一个程序,接收文件路径和“任务”作为输入,并根据输入的“任务”执行功能。
如果任务输入是“rev”,程序需要反向打印文件内容(包括行和词)。
我试过了:
def file_play():
file_path = input("Please enter a file path: ")
task = input("Please enter a task: ")
my_file = open(file_path, "r")
if task == "rev":
for line in my_file:
for word in line.split():
print(word[::-1], end=" ")
my_file.close()
文件中的文本:
i believe i can fly i believe i can touch the sky
i think about it every night and day spread my wings and fly away
当前输出:
i eveileb i nac ylf i eveileb i nac hcuot eht yks i kniht tuoba ti yreve thgin dna yad daerps ym sgniw dna ylf yawa
所需输出:
yks eht hcuot nac i eveileb i ylf nac i eveileb i
yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i
您正在颠倒每个单词。你想要的是像这样反转线:
def file_play():
file_path = input("Please enter a file path: ")
task = input("Please enter a task: ")
my_file = open(file_path, "r")
if task == "rev":
for line in my_file:
print(line[::-1])
my_file.close()
你可以把线倒过来:
task = ['i believe i can fly i believe i can touch the sky', 'i think about it every night and day spread my wings and fly away']
for line in task:
print(line[::-1], end='\n')
输出
yks eht hcuot nac i eveileb i ylf nac i eveileb i
yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i
如果是字符串,则先转成列表
a = "Hack it"
a = list(a)
a.reverse()
b = ""
for i in range(len(a)):
b += a[i]
print("Reversed string/list: " + b)
输出:
Reversed string/list: ti kcaH
真心希望这对您有所帮助!
要写一个程序,接收文件路径和“任务”作为输入,并根据输入的“任务”执行功能。 如果任务输入是“rev”,程序需要反向打印文件内容(包括行和词)。
我试过了:
def file_play():
file_path = input("Please enter a file path: ")
task = input("Please enter a task: ")
my_file = open(file_path, "r")
if task == "rev":
for line in my_file:
for word in line.split():
print(word[::-1], end=" ")
my_file.close()
文件中的文本:
i believe i can fly i believe i can touch the sky
i think about it every night and day spread my wings and fly away
当前输出:
i eveileb i nac ylf i eveileb i nac hcuot eht yks i kniht tuoba ti yreve thgin dna yad daerps ym sgniw dna ylf yawa
所需输出:
yks eht hcuot nac i eveileb i ylf nac i eveileb i
yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i
您正在颠倒每个单词。你想要的是像这样反转线:
def file_play():
file_path = input("Please enter a file path: ")
task = input("Please enter a task: ")
my_file = open(file_path, "r")
if task == "rev":
for line in my_file:
print(line[::-1])
my_file.close()
你可以把线倒过来:
task = ['i believe i can fly i believe i can touch the sky', 'i think about it every night and day spread my wings and fly away']
for line in task:
print(line[::-1], end='\n')
输出
yks eht hcuot nac i eveileb i ylf nac i eveileb i
yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i
如果是字符串,则先转成列表
a = "Hack it"
a = list(a)
a.reverse()
b = ""
for i in range(len(a)):
b += a[i]
print("Reversed string/list: " + b)
输出:
Reversed string/list: ti kcaH
真心希望这对您有所帮助!