Skip to content

Cannot concatenate 'str' and 'java.lang.String' #195

Closed

Description

@yogi1967

In the below, line 5 displays correctly, line 6 displays garbage, line 7 errors... Only "%s" %(theStr) works instead of str()

from javax.swing import JOptionPane, JLabel
from java.lang import String
euroSymb=String(u"\u20ac")
gbpSymb=String(u"\u00A3")
JOptionPane.showMessageDialog(None, JLabel("Symbols: %s %s" %(euroSymb, gbpSymb)), "test", JOptionPane.INFORMATION_MESSAGE, None)
JOptionPane.showMessageDialog(None, JLabel("Symbols: " + str(euroSymb)+str(gbpSymb)), "test", JOptionPane.INFORMATION_MESSAGE, None)
print "Symbols: " + str(currSymb) + str(gbpSymb)

Activity

  1. jeff5 commented on Jul 3, 2022

    @jeff5
    Member

    Do you have to use Java String for this?

    What's wrong with euroSymb = u"\u20ac"? Or even:

    JOptionPane.showMessageDialog(None, JLabel(u"Symbols: € £" ), "test", JOptionPane.INFORMATION_MESSAGE, None)
    

    with an encoding declaration, of course.

    JLabel ought to receive a java.lang.String automatically. If it doesn't, that's a more sensible bug to fix. (I haven't tested any of this.)

  2. changed the title [-]Concatenation of str and String, also str and unicode causes garbage output or 'TypeError: cannot concatenate 'str' and 'java.lang.String' objects' error[/-] [+]Cannot concatenate 'str' and 'java.lang.String'[/+] on Jul 3, 2022
  3. jeff5 commented on Jul 3, 2022

    @jeff5
    Member

    Ideally we would get the same behaviour in Jython towards Java String that CPython has towards unicoode. There may be limitations that follow from String sometimes meaning str. (History.)

    CPython:

    Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> euroSymb=u"\u20ac"
    >>> str(euroSymb)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
    >>> "%s" % euroSymb
    u'\u20ac'
    >>>
    

    Jython (development tip):

    Jython 2.7.3a1-DEV (heads/non-byte-str-optimisation:8e2cdf623, Jul 3 2022, 08:45:03)
    [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_321
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from java.lang import String
    >>> euroSymb=String(u"\u20ac")
    >>> str(euroSymb)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
    >>> "%s" % euroSymb
    u'\u20ac'
    

    LGTM. That last bit may be thanks to #192.

  4. yogi1967 commented on Jul 3, 2022

    @yogi1967
    Author

    Hi, surely the point is that these lines don't work? My code was pure example to force the issue for you as a demo.

    Anyway, the reason being that my Jython code is an extension that sits within a pure java application. I have no control over the java app. All the data comes from the app and is always UTF8/Unicode. Hence I have to deal with it.. I.e. I receive a java stored String that has utf8/unicode contents...

  5. jeff5 commented on Jul 3, 2022

    @jeff5
    Member

    You may have a point with:

    >>> "money " + euroSymb
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: cannot concatenate 'str' and 'java.lang.String' objects
    >>> u"money " + euroSymb
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: cannot concatenate 'unicode' and 'java.lang.String' objects
    

    But I'm not sure it needs work when we have a perfectly good type in unicode. str(euroSymb) shouldn't work. unicode(euroSymb) works fine.

    If the data arrive as UTF-8, then there are codecs.

  6. yogi1967 commented on Jul 3, 2022

    @yogi1967
    Author

    Surely if "money %s" %(euroSymb) works, then "money" + str(euroSymb) should work? It shouldn't crash or return garbage..? It seems a bit crazy that I have to create my own method called safeStr(x) which returns "%s" %(x) to get round the random garbage or exceptions caused by str() in these scenarios..?

  7. jeff5 commented on Jul 3, 2022

    @jeff5
    Member

    I'm afraid we're dealing with Python 2 here. (You do realise I hope?) str holds bytes. If we give it characters, it cannot be expected to know what bytes to turn them into on its own.

    As a concession to 50 years of anglo-centric programming, and the fact that all supported codecs agree for the first 128 characters, it will try US-ASCII. Hence the error message is about the 'ascii' codec.

    I think your code should be written using unicode objects. If you're used to Python 3, you'll hardly have had to think about bytes, because the Python 3 str is unicode.

    str(euroSymb) should be an error and it is in both implementations. You asked for a str and it can't be done without guesswork. In contrast, "money %s" % euroSymb works because the formatter gets to the %s argument, realises it is unicode and decides to give you a unicoderesult.

    If your data arrive as Java String, then turn them into unicode like this: unicode(euroSymb). When you pass a unicode value to a Java call that expects String it should get coerced automatically.

    If your data arrive as bytes, they might be in a str or in an array.array, and you need to decode them. You can pass a str to a Java method but it won't go well unless it's US-ASCII. Generally you will have to convert them to Unicode with:

    >>> '\xe2\x82\xac'.decode('utf-8')
    u'\u20ac'
    
  8. yogi1967 commented on Jul 3, 2022

    @yogi1967
    Author

    😂 - yes I am very aware I'm using Python 2.7... I come from a background where I was a Basic/Cobol/DBase programmer 30+ years ago, and recently had to learn Java, Python, Jython, and the application's API just to get an extension working.. YUP - Unicode and UTF8 was a complete mystery, but I cobbled something together... I'm much more experienced now. This was an issue that first hit me...I still don't think Jython should cause an exception or show different results depending on how you achieve the same thing... Anyway, I'll have a think about what you said - thanks

  9. yogi1967 commented on Jul 3, 2022

    @yogi1967
    Author

    thanks for the great unicode(txt) tip.. It does seem to work better.. One day I will perhaps understand bytes vs characters.

    So under the covers is "%s" %(txt) actually doing the same as unicode(txt) and also the same as repr(txt)..?

  10. jeff5 commented on Jul 3, 2022

    @jeff5
    Member

    So under the covers is "%s" %(txt) actually doing the same as unicode(txt) and also the same as repr(txt)..?

    Not really. You ask the object's __format__ method, passing it the %s specification.
    The PyString or PyUnicode first produce their string contents for truncations and padding. The whole thing works in chars, but it remembers whether it is supposed to produce a str or unicodeat the end.

    // Bytes mode if neither this nor formatSpec argument is Unicode.
    boolean unicode = this instanceof PyUnicode || formatSpec instanceof PyUnicode;
    f.setBytes(!unicode);
    // Convert as per specification.
    f.format(getString());
    // Return a result that has the same type (str or unicode) as the formatSpec argument.
    return f.pad().getPyResult();

    The last comment is wrong: result type depends on the bytes flag, which you can see depends on the type of argument as well as the type of format string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions