473,804 Members | 3,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting a string to an array?

While working on a Jumble-esque program, I was trying to get a
string into a character array. Unfortunately, it seems to choke
on the following

import random
s = "abcefg"
random.shuffle( s)

returning

File "/usr/lib/python2.3/random.py", line 250, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: object doesn't support item assignment

The closest hack I could come up with was

import random
s = "abcdefg"
a = []
a.extend(s)
random.shuffle( a)
s = "".join(a)

This lacks the beauty of most python code, and clearly feels like
there's somethign I'm missing. Is there some method or function
I've overlooked that would convert a string to an array with less
song-and-dance? Thanks,

-tim

Jan 12 '06 #1
6 3058
Tim Chase wrote:
The closest hack I could come up with was

import random
s = "abcdefg"
a = []
a.extend(s)
random.shuffle( a)
s = "".join(a)

This lacks the beauty of most python code, and clearly feels like
there's somethign I'm missing. Is there some method or function
I've overlooked that would convert a string to an array with less
song-and-dance? Thanks,

-tim


Would
import random
s = "abcdefg"
data = list(s)
random.shuffle( data)
"".join(dat a) 'bfegacd'


fit you better?
Jan 12 '06 #2
> >>> import random
>>> s = "abcdefg"
>>> data = list(s)
>>> random.shuffle( data)
>>> "".join(dat a)

'bfegacd'

fit you better?


Excellent! Thanks. I kept trying to find something like an
array() function. Too many languages, too little depth.

The program was just a short script to scramble the insides of
words to exercise word recognition, even when the word is mangled.

It's amazing how little code it takes to get this working.

When using it as a filter, if a downstream pipe (such as "head")
cuts it off, I get an error:

bash# ./scramble.py bigfile.txt | head -50

[proper output here]

Traceback (most recent call last):
File "./scramble.py", line 11, in ?
print r.sub(shuffleWo rd, line),
IOError: [Errno 32] Broken pipe

At the moment, I'm just wrapping the lot in a try/except block,
and ignoring the error. Is there a better way to deal with this
gracefully? If some more serious IO error occurred, it would be
nice to not throw that baby out with the bath-water. Is there a
way to discern a broken pipe from other IOError exceptions?

Thanks again.

-tim

import random, sys, re
r = re.compile("[A-Za-z][a-z]{3,}")
def shuffleWord(mat chobj):
s = matchobj.group( 0)
a = list(s[1:-1])
random.shuffle( a)
return "".join([s[0], "".join(a), s[-1]])
try:
for line in sys.stdin.readl ines():
print r.sub(shuffleWo rd, line),
except IOError:
pass


Jan 12 '06 #3
Tim Chase wrote:
>>> import random
>>> s = "abcdefg"
>>> data = list(s)
>>> random.shuffle( data)
>>> "".join(dat a)

'bfegacd'

fit you better?


Excellent! Thanks. I kept trying to find something like an
array() function. Too many languages, too little depth.

from array import array
a = array('c', "abcdefgh")
a array('c', 'abcdefgh') import random
random.shuffle( a)
a array('c', 'gfecdabh') a.tostring()

'gfecdabh'

</F>

Jan 13 '06 #4
Tim Chase wrote:
While working on a Jumble-esque program, I was trying to get a string
into a character array. Unfortunately, it seems to choke on the following

import random
s = "abcefg"
random.shuffle( s)

returning

File "/usr/lib/python2.3/random.py", line 250, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: object doesn't support item assignment


Yes, Python has had that same problem elsewhere, notably the
mutating methods 'sort' and 'reverse'. Those problems are now
reasonably well solved. What's really neat is that the names
of the new methods: 'sorted' and 'reversed', are adjectives
describing the return values we want, where 'sort' and
'reverse' are verbs, calling for procedures to be performed.
For sorting, we had the procedure 'sort', then added the pure
function 'sorted'. We had a 'reverse' procedure, and wisely
added the 'reversed' function.

Hmmm... what we could we possible do about 'shuffle'?
--
--Bryan
Jan 13 '06 #5
Tim Chase <py*********@ti m.thechases.com > writes:
The closest hack I could come up with was

import random
s = "abcdefg"
a = []
a.extend(s)
random.shuffle( a)
s = "".join(a)


You could use

import random
s = list("abcdefg")
random.shuffle( s)
s = "".join(s)

which cuts down the clutter slightly.
Jan 13 '06 #6
[Bryan Olson]
...
For sorting, we had the procedure 'sort', then added the pure
function 'sorted'. We had a 'reverse' procedure, and wisely
added the 'reversed' function.

Hmmm... what we could we possible do about 'shuffle'?


'permuted' is the obvious answer, but that would leave us open to more
charges of hifalutin elitism, so the user-friendly and slightly risque
'jiggled' it is.

sorry-it-can't-be-'shuffled'-we-ran-out-of-'f's-ly y'rs - tim
Jan 13 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
13930
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do something like: char chars = "Hello!"; byte bytes = (byte) chars;
4
412
by: x | last post by:
converting 1944 to '1','9','4','4' how can I convert a number such as 1944 to a character array? thanks!
2
5755
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
4
5404
by: Prabhu | last post by:
Hi, We are having problem in converting a byte array to string, The byte array has char(174), char(175), char(240), char(242) and char(247) as delimiters for the message. when we use "System.Text.Encoding.ASCII.GetString(bytearray)" of .Net library, we found that the char (delimiters) specified above are replaced with different char.
8
4570
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in XML, and embedded the array as some child element in an xml file, i.e.: <Mask>bHQAAH4AAABCTX4AAAAAAAAAPgAAACgAAAAQAAAAEAAAAAEAAQAAAAAAQAAAAAAAAAAAAA AA AAAAAAAAAAAAAAAA////AP//AAD//wAA//8AAP//AAD/7wAA//cAALtzAABVeQAAVUAAAFVA...
4
2266
by: sal | last post by:
Greets, All Converting array formula to work with datatables/dataset tia sal I finally completed a formula I was working on, see working code below. I would like to change this code so it will work with a variable mutl- row, 5 column datatable where the users select items. Anyone have any suggestions on where to start? Or changes in the current code that might be made.
8
4207
by: moondaddy | last post by:
I need to convert a byte array to a string and pass it as a parameter in a URL and then convert it back to the original byte array. However, its getting scrambled in the conversion. In short, here's the code: ====================================== Dim textConverter As New ASCIIEncoding Dim sParam As String = "This is my cool param" Dim bytParam() As Byte 'load the byte array here...
2
2336
by: XML newbie: Urgent pls help! | last post by:
Does anyone have a snippet of code that will convert a string to a long array? I've nearly smashed my head against the wall trying to figure this out. I'm Using vb.net 2005 Pls reply asap. I thaanku all in advance. God bless u.
4
3197
by: gg9h0st | last post by:
i'm a newbie studying php. i was into array part on tutorial and it says i'll get an array having keys that from member variable's name by converting an object to array. i guessed "i can get public members but not protected, private, static members"
2
11187
by: Brian Parker | last post by:
I am beginning to work with VB2005.NET and I'm getting some problems with string formatting converting an application from VB6. VB6 code:- sTradeDate = Format(pArray(4,i Record), "mmddyy") pArray is a variant array containing a date string at pArray(4, iRecord) in the format "yyyy/mm/dd"
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10578
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9152
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5522
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.