2011-12-02 79 views
7

编写一个简单的程序,用于从键盘读取一行,并输出相同的行,其中每个单词都被反转 。一个词被定义为连续的字母数字字符序列 或连字符(' - ')。举例来说,如果输入的是 “你能帮帮我吧!” 输出应该是 “NAC uoy pleh他们!”Python中的字符串反转

我只是tryed用下面的代码,但也有一些问题吧,

print"Enter the string:" 
str1=raw_input() 
print (' '.join((str1[::-1]).split(' ')[::-2])) 

它打印“naC uoy pleh!em”,只是看感叹号(!),这里是问题所在。任何人都可以帮助我?

回答

3

您可以使用re.sub()找到每个单词并将其逆转:

In [8]: import re 

In [9]: s = "Can you help me!" 

In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s) 
Out[10]: 'naC uoy pleh em!' 
+0

的单词,在我看来这是一个不错的方法。 – phimuemue

+0

注意''\ w''表示字母数字**和下划线**,而OP没有将单词定义为可能包含下划线 – eyquem

-1

你可以这样做。

print"Enter the string:" 

str1=raw_input() 

print(' '.join(str1[::-1].split(' ')[::-1])) 

或然后,这个

print(' '.join([w[::-1] for w in a.split(' ') ])) 
+0

输出会完全像什么OP已经有: “NAC uoy pleh他们!”。 –

6

最简单的可能是使用re模块分割字符串:

import re 
pattern = re.compile('(\W)') 
string = raw_input('Enter the string: ') 
print ''.join(x[::-1] for x in pattern.split(string)) 

运行时,你会得到:

Enter the string: Can you help me! 
naC uoy pleh em! 
+1

这在包含连字符的字符串中不起作用。我认为这个模式应该改成re.compile('([^ \ w \ - ])') –

+0

''(\ W +)''会比''(\ W)更好 - 注意\ W象征着除字母数字和下划线之外的其他字符,而OP没有定义一个可能包含下划线 – eyquem

0

我的答案,虽然更详细。它处理结尾处的多个标点符号以及句子中的标点符号。

import string 
import re 

valid_punctuation = string.punctuation.replace('-', '') 
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$') 

# reverses word. ignores punctuation at the end. 
# assumes a single word (i.e. no spaces) 
def word_reverse(w): 
    m = re.match(word_pattern, w) 
    return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1] 

def sentence_reverse(s): 
    return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)]) 

str1 = raw_input('Enter the sentence: ') 
print sentence_reverse(str1) 
0

不使用re模块简单的解决方案:

print 'Enter the string:' 
string = raw_input() 

line = word = '' 

for char in string: 
    if char.isalnum() or char == '-': 
     word = char + word 
    else: 
     if word: 
      line += word 
      word = '' 
     line += char 

print line + word