在 python 中反转给定字符串中的单词
reverse words in a given string in python
我已经在 python 中编写了代码,如果我将整数作为输入,它可以正常工作,但如果给出字符串,则不会。
例子-
输入:
2
i.like.this.program.very.much
pqr.mno
预期输出:
much.very.program.this.like.i
mno.pqr
但我得到的输出与输入相同。字符串没有反转。
我写的代码是-
t=int(input())
for i in range(t):
string1=input()
li1=string1.split()
li2=li1[::-1]
output=' '.join(li2)
print(output)
在 运行 以上输入后,我得到 -
输出:
i.like.this.program.very.much
pqr.mno
输出错误的原因
您的程序无法正常工作的原因是因为您试图在 space 字符处拆分字符串,这是 split()
的默认字符当没有指定参数时。但是你真的想在 '.'
个字符处拆分你的字符串。
所以当你尝试 string1.split()
时,你得到的列表是 -
['i.like.this.program.very.much']
而我们真正想要获得正确输出的是 -
['i', 'like', 'this', 'program', 'very', 'much']
我们使用 string1.split('.')
得到的正确结果是在 .
字符处拆分字符串,然后反转字符串。请注意,在加入字符串时,我们也必须使用 .
加入它。
所以你应该修改你的代码如下。
正确的代码 -
t=int(input())
for i in range(t):
string1=input()
li1=string1.split('.') #<-- Notice the parameter specified here. It will now split at `.` character
li2=li1[::-1] # Reverse the list
output='.'.join(li2) # Convert back into string. Again notice, we are joining at . character to get expected output
print(output)
输入:
2
i.like.this.program.very.much
pqr.mno
输出:
much.very.program.this.like.i
mno.pqr
希望对您有所帮助!
s = input("Enter string here = ")
l1=s.split
l1.reverse()
print(l1)
我已经在 python 中编写了代码,如果我将整数作为输入,它可以正常工作,但如果给出字符串,则不会。
例子-
输入:
2
i.like.this.program.very.much
pqr.mno
预期输出:
much.very.program.this.like.i
mno.pqr
但我得到的输出与输入相同。字符串没有反转。 我写的代码是-
t=int(input())
for i in range(t):
string1=input()
li1=string1.split()
li2=li1[::-1]
output=' '.join(li2)
print(output)
在 运行 以上输入后,我得到 -
输出:
i.like.this.program.very.much
pqr.mno
输出错误的原因
您的程序无法正常工作的原因是因为您试图在 space 字符处拆分字符串,这是 split()
的默认字符当没有指定参数时。但是你真的想在 '.'
个字符处拆分你的字符串。
所以当你尝试 string1.split()
时,你得到的列表是 -
['i.like.this.program.very.much']
而我们真正想要获得正确输出的是 -
['i', 'like', 'this', 'program', 'very', 'much']
我们使用 string1.split('.')
得到的正确结果是在 .
字符处拆分字符串,然后反转字符串。请注意,在加入字符串时,我们也必须使用 .
加入它。
所以你应该修改你的代码如下。
正确的代码 -
t=int(input())
for i in range(t):
string1=input()
li1=string1.split('.') #<-- Notice the parameter specified here. It will now split at `.` character
li2=li1[::-1] # Reverse the list
output='.'.join(li2) # Convert back into string. Again notice, we are joining at . character to get expected output
print(output)
输入:
2
i.like.this.program.very.much
pqr.mno
输出:
much.very.program.this.like.i
mno.pqr
希望对您有所帮助!
s = input("Enter string here = ")
l1=s.split
l1.reverse()
print(l1)