Splitting a string into groups of three characters

L

lemon97

Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.

Thank You,
 
J

John Machin

Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.

Thank You,

Maybe, somewhere out there -- you could write one yourself, like this:

# untested
def nsplit(s, n):
return [s[k:k+n] for k in xrange(0, len(s), n)]
 
L

lemon97

Thank You, For your help,
I guess I will just make a couple of these functions and find out
which one is that fastest.
 
T

Terry Reedy

Is there a function that split a string into groups, containing an "x"
amount of characters?

There have been previous threads giving various solutions (which generally
are not specific to strings). You might find some some by searching the
Google archive of this group. Some of the variations depend on what to do
if len(s) % x != 0. Do you pad to x, drop the extras, or return a
deficient group?

Terry J. Reedy
 
D

Dennis Lee Bieber

Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']
Uhm... You're output doesn't match your requirements <G>

["Hel", "lo ", "Wor", "ld"]

--
 
J

John Machin

gene said:
Um, you shd 1st search cookbook, or Vaults Parnassu, dmoz python
section, pypackage:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689

which includes e.g.

def each_slice_lol(listin,n):
"""non-overlapp'g slices, return (list of lists) """
len_listin=len(listin)
return [listin[i:min(len_listin, i+n)] for i in range(0,len_listin,n)]

and the listin[i:min(len_listin, i+n)] is grossly wasteful; it does
EXACTLY the same as listin[i:i+n] for the values of i and n that make sense.

From the Python reference manual:
"""The semantics for a simple slicing are as follows. The primary must
evaluate to a sequence object. The lower and upper bound expressions, if
present, must evaluate to plain integers; defaults are zero and the
sys.maxint, respectively. If either bound is negative, the sequence's
length is added to it. The slicing now selects all items with index k
such that i <= k < j where i and j are the specified lower and upper
bounds. This may be an empty sequence. It is not an error if i or j lie
outside the range of valid indexes (such items don't exist so they
aren't selected).
"""
 
M

Maksim Kasimov

import re
str = '123456789983qw'
re.findall("(.{3})", str)+[str[-(len(str) % 3):]]

Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.

Thank You,
 
L

lemon97

Yes i know i made a mistake,
['Hell','o W','orl','d']
but you know what I mean lol,

I'll probly use
John Machin's

def nsplit(s, n):
return [s[k:k+n] for k in xrange(0, len(s), n)]

It seems fast, and does not require any imports.

But anyways, thank you for all your help, you rpck! :)
 
L

lemon97

Yes i know i made a mistake,
['Hell','o W','orl','d']
but you know what I mean lol,

I'll probly use
John Machin's

def nsplit(s, n):
return [s[k:k+n] for k in xrange(0, len(s), n)]

It seems fast, and does not require any imports.

But anyways, thank you for all your help, you rock! :)
 
W

William Park

Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.

Look into 're' module. Essentially, split using '...', but return the
separator as well. Then, remove empty items. In Bash shell, you would
do
a="Hello World"
set -- "${a|?...}" # extract '...' separators
pp_collapse # remove null items
printf '{%s}\n' "${@}"

Translating to Python is left as homework.

--
William Park <[email protected]>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
 
?

=?ISO-8859-1?Q?Gregory_Pi=F1ero?=

I guess this question has already been thouroughly answered but here
is my version:

def split(string,n):
outlist=[]
for bottom in range(0,len(string),n):
top=min(bottom+n,len(string))
outlist.append(string[bottom:top])
return outlist




Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.

Look into 're' module. Essentially, split using '...', but return the
separator as well. Then, remove empty items. In Bash shell, you would
do
a="Hello World"
set -- "${a|?...}" # extract '...' separators
pp_collapse # remove null items
printf '{%s}\n' "${@}"

Translating to Python is left as homework.

--
William Park <[email protected] >, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
 
J

John Machin

William said:
Hi,

Is there a function that split a string into groups, containing an "x"
amount of characters?

Ex.
TheFunction("Hello World",3)

Returns:

['Hell','o W','orl','d']


Any reply would be truly appreciated.


Look into 're' module. Essentially, split using '...', but return the
separator as well. Then, remove empty items. In Bash shell, you would

This would have to be a candidate for arcane side-effect of the month.
Not in front of the children, please.
do
a="Hello World"
set -- "${a|?...}" # extract '...' separators
pp_collapse # remove null items
printf '{%s}\n' "${@}"

Translating to Python is left as homework.

Given that the OP was struggling to write a simple loop in Python,
giving him an answer in hieroglypghics and suggesting he translate it
into Python could be described as unhelpful.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top