[Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid"

Max Noel maxnoel_fr at yahoo.fr
Mon Nov 22 02:41:46 CET 2004


On Nov 22, 2004, at 01:28, Fabian von Berlepsch wrote:

> Hallo Guys,
>
> I am almost having a nerve crisis!
> Since 3 hours I am trying to find the python equivalent for VB6 "left",
> "right" and "mid".

	What you're looking for is the slicing operator. Each character in a 
string is numbered from 0 to len - 1.
 >>> foo = "Hello World!"
 >>> len(foo)
12

	You have to use foo[start:finish:step], where start is the first 
character you want, finish is the first character you don't want, and 
step is the step of the slice (step = 2 will take one character every 
two chars). You can omit finish and step if you don't want them.
	Also, you can use negative numbers to count from the end of the 
string, e.g. while foo[0] is the first character of the string, foo[-1] 
is the last one.
	Here are a few examples:
 >>> foo = "Hello World!"
 >>> foo[0:5]
'Hello'
 >>> foo[1:5]
'ello'
 >>> foo[5:]
' World!'
 >>> foo[:5]
'Hello'
 >>> foo[:-1]
'Hello World'
 >>> foo[:-2]
'Hello Worl'
 >>> foo[1]
'e'
 >>> foo[-1]
'!'
 >>> foo[::2]
'HloWrd'

	This also works with lists and tuples.

Hope that helped,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"



More information about the Tutor mailing list