简体   繁体   中英

How to reverse the words of a string considering the punctuation?

Here is what I have so far:

def reversestring(thestring):
    words = thestring.split(' ')
    rev = ' '.join(reversed(words))
    return rev

stringing = input('enter string: ')
print(reversestring(stringing))

I know I'm missing something because I need the punctuation to also follow the logic.

So let's say the user puts in Do or do not, there is no try. . The result should be coming out as .try no is there, not do or Do , but I only get try. no is there not, do or Do try. no is there not, do or Do . I use a straightforward implementation which reverse all the characters in the string, then do something where it checks all the words and reverses the characters again but only to the ones with ASCII values of letters.

Your code does exactly what it should, splitting on space doesn't separator a dot ro comma from a word.


I'd suggest you use re.findall to get all words, and all punctation that interest you

import re
def reversestring(thestring):
    words = re.findall(r"\w+|[.,]", thestring)
    rev = ' '.join(reversed(words))
    return rev

reversestring("Do or do not, there is no try.")  # ". try no is there , not do or Do"

Try this (explanation in comments of code):

s = "Do or do not, there is no try."

o = []
for w in s.split(" "):
  puncts = [".", ",", "!"] # change according to needs
  for c in puncts:
    # if a punctuation mark is in the word, take the punctuation and add it to the rest of the word, in the beginning
    if c in w:
      w = c + w[:-1] # w[:-1] gets everthing before the last char
  
  o.append(w)
  

o = reversed(o) # reversing list to reverse sentence
print(" ".join(o)) # printing it as sentence


#output: .try no is there ,not do or Do

You can use regular expressions to parse the sentence into a list of words and a list of separators, then reverse the word list and combine them together to form the desired string. A solution to your problem would look something like this:

import re

def reverse_it(s):
    t = "" # result, empty string
    words = re.findall(r'(\w+)', s) # just the words
    not_s = re.findall(r'(\W+)', s) # everything else
    j = len(words)
    k = len(not_s)
    words.reverse() # reverse the order of word list
    if re.match(r'(\w+)', s): # begins with a word
        for i in range(k):
            t += words[i] + not_s[i]
        if j > k: # and ends with a word
            t += words[k]
    else: # begins with punctuation
        for i in range(j):
            t += not_s[i] + words[i]
        if k > j: # ends with punctuation
            t += not_s[j]
    return t #result

def check_reverse(p):
    q = reverse_it(p)
    print("\"%s\", \"%s\"" % (p, q) )

check_reverse('Do or do not, there is no try.')

Output

"Do or do not, there is no try.", "try no is there, not do or Do."

It is not a very elegant solution but sure does work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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