简体   繁体   English

反转 python 中给定字符串中的单词

[英]reverse words in a given string in python

I have written the code in python it works fine if I give integer as an input but it does not when string is given.我已经在 python 中编写了代码,如果我将 integer 作为输入,它可以正常工作,但在给出字符串时它不会。

Example -例子 -

Input:输入:

2
i.like.this.program.very.much
pqr.mno

Expected Output:预期 Output:

much.very.program.this.like.i
mno.pqr

But the output which I get is same as input.但是我得到的 output 与输入相同。 The string is not getting reversed.字符串没有反转。 The code I have written is -我写的代码是 -

t=int(input())
for i in range(t):
    string1=input()
    li1=string1.split()
    li2=li1[::-1]
    output=' '.join(li2)
    print(output)

After running for the above input I get -运行上述输入后,我得到 -

Output: Output:

i.like.this.program.very.much
pqr.mno

Cause of Wrong Output错误原因 Output

The reason your program doesn't work correctly is because you are trying to split the string at space character which is the default for split() when no parameter is specified.您的程序无法正常工作的原因是因为您试图在空格字符处拆分字符串,这是未指定参数时split()的默认值。 But you are really looking to split your string at '.'但是您真的希望在'.'处拆分字符串。 character.特点。

So when you try string1.split() , the list you get is -因此,当您尝试string1.split()时,您得到的列表是 -

['i.like.this.program.very.much']

while what we really want to get the correct output is -而我们真正想要得到正确的 output 是 -

['i', 'like', 'this', 'program', 'very', 'much']

which we get correctly using string1.split('.') , that is splitting the string at .我们使用string1.split('.')得到正确的结果,即在 .split('.') 处拆分字符串. character and then reversing the string.字符,然后反转字符串。 Do note that while joining the string, we would have to join it using .请注意,在加入字符串时,我们必须使用. as well.以及。


So you should modify your code as follows.所以你应该如下修改你的代码。

Correct Code -正确的代码 -

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)

Input:输入:

2
i.like.this.program.very.much
pqr.mno

Output: Output:

much.very.program.this.like.i
mno.pqr

Hope this helps !希望这可以帮助 !

s = input("Enter string here = ")
l1=s.split
l1.reverse()
print(l1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM