0

Try to get a class which would work like so:

>>> original = u"ABCD-123-foo"
>>> suffix = SuffixComparingUnicodeString("foo")
>>> suffix == original    # if original ends with suffix, True
True

I know it's silly. Please bear with me.

Anyway, I can't figure out how to get the actual, er, string (not str, mind) from within the unicode object. I can do it like this just fine:

>>> class SuffixComparingUnicodeString(unicode):
...     def __init__(self, x):
...          super(SuffixComparingUnicodeString, self).__init__(x)
...          self._myval = x
...     def __eq__(self, other):
...          return isinstance(other, unicode) and other.endswith(self._myval)
...
>>> SuffixComparingUnicodeString("foo") == u"barfoo"
True

How can I do it without storing that value myself? What does unicode call its underlying character sequence?

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • I'm sorry, what's your question? How to get the non-unicode version of the string you used to initialize it? – agf Jul 31 '13 at 22:12
  • 1
    `unicode` calls its "underlying string" `self`. It's like trying to get the `3` out of a `3` object. If you want an instance of `unicode`, you can use `unicode(self)`. – user2357112 Jul 31 '13 at 22:17
  • @agf I'm asking: if you have `myuni = unicode("foo")`, what is the member `unicode` uses to talk about `u"foo"` inside the `myuni` instance? It's hard for me to articulate it, but, I feel like it's pretty clear what I'm asking otherwise. – 2rs2ts Jul 31 '13 at 22:17

1 Answers1

2

Since you a subclassing unicode, instances of SufficComparingUnicodeString can usually be used just like any other Unicode string. So you can just use other.endswith(self) in your __eq__() implementation:

class SuffixComparingUnicodeString(unicode):
    def __eq__(self, other):
        return isinstance(other, unicode) and other.endswith(self)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306