Python str.join() concatenation scrambling

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
entorri

Python str.join() concatenation scrambling

Post by entorri »

coding a StreamWriter() in Python like builder = StringIO.StringIO() found this interesting
# FAILS
>>> str.join('as %s','dfg')
'das %sfas %sg'
# WORKS
>>> a = """a %s d %s f""" %('da' , 'da')
>>> a
'a da d da f'
----------------
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Linux foo 3.2.0-23-generic #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux / 3.5 Bogomips
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 2 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
xenopeek
Level 25
Level 25
Posts: 29612
Joined: Wed Jul 06, 2011 3:58 am

Re: Python str.join() scrap

Post by xenopeek »

Moved here by moderator

That is not how you are supposed to use str.join(), you have given the iterable to join but not the separator string. http://docs.python.org/library/stdtypes.html#str.join. What are you actually trying to do? This works as expected:

Code: Select all

>>> " da ".join("adf")
'a da d da f'
Image
Jamesc359

Re: Python str.join() scrap

Post by Jamesc359 »

You need to remember that Python is heavily object oriented. As such a string is treated as an object and join is one of it's many methods.

As shown in the docs the str part of str.join() is used as a symbolic represention for a string object. Creating a real string object for use in actual code is simple.

Code: Select all

l = ["Hello", "World"] # List Object
s = " " # String Object

print s.join(l)
print "_".join(l)
This should produce;
Hello World
Hello_World


I hope that makes sense. :)
entorri

Re: Python str.join() concatenation scrambling

Post by entorri »

nope it doesn't

i'm pretty sure it's a memory scrambling bug maybe from python's build
* the data scrambles from the end of the string to be joint to the start of the initial string.

the sentence works for a SQLite3 SELECT * and is not working at any point it scrambles the last characters to the first of the sentence.

i'm not using Python SQLite statement joiner since it makes another whole different kind of string concatenation errors
Locked

Return to “Scripts & Bash”