Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的字符串反转_Python - Fatal编程技术网

Python中的字符串反转

Python中的字符串反转,python,Python,编写一个简单的程序,从键盘上读取一行,并在其中输出同一行 每个字都是颠倒的。单词定义为字母数字字符的连续序列 或连字符('-')。例如,如果输入是 “你能帮帮我吗?” 输出应该是 “请不要这样!” 我刚刚试过下面的代码,但是有一些问题 print"Enter the string:" str1=raw_input() print (' '.join((str1[::-1]).split(' ')[::-2])) 它打印“naC uoy pleh!em”,看看感叹号(!),这就是问题所在。有人能

编写一个简单的程序,从键盘上读取一行,并在其中输出同一行 每个字都是颠倒的。单词定义为字母数字字符的连续序列 或连字符('-')。例如,如果输入是 “你能帮帮我吗?” 输出应该是 “请不要这样!”

我刚刚试过下面的代码,但是有一些问题

print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))
它打印“naC uoy pleh!em”,看看感叹号(!),这就是问题所在。有人能帮我吗

你可以这样做

print"Enter the string:"

str1=raw_input()

print( ' '.join(str1[::-1].split(' ')[::-1]) )
或者,这个

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

最简单的方法可能是使用
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!
您可以使用查找每个单词并将其反转:

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!'

我的回答更冗长。它在句末处理多个标点符号以及句子中的标点符号

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)

不使用
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

输出将与OP已有的完全相同:“naC uoy pleh!em”。这在包含连字符的字符串上无法正常工作。我认为模式应该改为重新编译(“([^\w \-]))
(\w+)
(\w)
更好-注意\w表示字母数字字符和下划线以外的其他字符,而OP没有将单词定义为可能包含下划线这是一种很好的方式,在我看来。请注意,
\w
表示字母数字和下划线,而OP没有将单词定义为可能包含下划线