1

I am writing a very simple function that, given a string as input, parses the string into sentences, reverses the words of each sentence, and returns the reversed sentences but in the given sentence order. I am struggling with the string.split() and string.join() built-in methods and am getting a TypeError when I run the following python program.

import string

def reverseSentences(str):
    senList = str.split('.')
    for i, item in enumerate(senList[:]):
        senList[i] = string.join(item.split(' ').reverse(), ' ')
    return string.join(senList, '.') + '.'

When I try to print a call to this function it gives me a generic TypeError. Thanks for enduring my n00bishness.

Thalatta
  • 4,510
  • 10
  • 48
  • 79
  • 1
    `string.join` is old cruft (and removed in newer Python versions) - use `' '.join(reversed(...))` –  Jun 19 '13 at 19:33

3 Answers3

2

item.split(' ').reverse() does not return the list, rather it does the reverse in place. So, your join is same as:

string.join(None, ' ')

Clearly a problem. You should rather use reversed() function:

string.join(reversed(item.split(' ')), ' ')

And rather than string.join function, use the method defined in string class in newer Python version.

' '.join(reversed(item.split(' '))
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Try

>> str = 'a1 b2'
>> ' '.join(x[::-1] for x in str.split())
'1a 2b'

In function form:

def reverseSentences(str):
  return ' '.join(x[::-1] for x in str.split())

Notice that x[::-1] is way faster than reversed() (Reverse a string in Python).

Community
  • 1
  • 1
Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325
  • 1
    I think, OP just needs - `' '.join(str.split()[::-1])`. You are reversing each word. – Rohit Jain Jun 19 '13 at 19:38
  • You are right! This description confused me "reverses the words of each sentence". And OP didn't give a example input/output. It was fun to quick code anyway :) – Felipe Hoffa Jun 19 '13 at 19:40
0

In line:

senList[i] = string.join(item.split(' ').reverse(), ' ')

.reverse() reverse items in list object itself but returns nothing, so you can't use join in this way.

divide this line in two:

import string

def reverseSentences(text):
    senList = text.split('.')
    for i, item in enumerate(senList[:]):
        splited = item.split(' ')
        splited.reverse()
        senList[i] = string.join(splited, ' ')
    return string.join(senList, '.') + '.'
Łukasz Zdun
  • 283
  • 1
  • 3
  • 6