Reputation: 11933
Problem: The function [self._oun(upsplit[.....]
in the code given below returns either a word (string) or a bool(FALSE). Now when the concatenation through + operator happens, it tries to concatenate a bool (say FALSE) with a string and hence fails with an exception (TypeError, concatenating bool with str). It works perfectly fine when a string is returned.
How can I change the code in a pythonic way to handle the above problem? I just tried putting an if statement before this code to check for the return value and then have two else statements, one if the returned value is bool and one with string (which does not look pythonic to me).
return ' '.join(upsplit[:word-1] +
[self._oun(upsplit[word-1], 1) +
'-' + upsplit[word] + '-']) + \
' '.join(upsplit[(word+1):])
EDIT:
If it returns FALSE I just want to append it with upsplit[word] and not the return value (which would be bool FALSE). Note that the function does not return TRUE. It either returns a modified string or it returns FALSE. If it returns FALSE than I just need to append the original string stored in upsplit[word].
Upvotes: 0
Views: 120
Reputation: 174624
return ' '.join(upsplit[:word-1] +
[self._oun(upsplit[word-1], 1) or upsplit[word] +
'-' + upsplit[word] + '-']) + \
' '.join(upsplit[(word+1):])
Upvotes: 2
Reputation: 39406
wrap the call to self._oun
in a str()
call. str on a bool makes a string representation ('True' or 'False'), on a string, it returns the argument unchanged.
return ' '.join(upsplit[:word-1] +
[str(self._oun(upsplit[word-1], 1)) +
'-' + upsplit[word] + '-']) + \
' '.join(upsplit[(word+1):])
After clarifying comment, the ternary operator in Python works as such:
a = ('a' if <test> else 'b')
in your case
(self._oun(upsplit[word-1], 1) if (self._oun(upsplit[word-1], 1) != False) else upsplit[word-1])
note that it requires 2 calls to _oun
, and it would be much simpler if _oun returned the orignal string rather than False.
Upvotes: 1