Extract the middle N chars of a string

Wildman best_lay at yahoo.com
Thu May 19 00:17:04 EDT 2016


On Thu, 19 May 2016 01:47:33 +1000, Steven D'Aprano wrote:

> Is this the simplest way to get the middle N characters?

This will return a sub-string of any length starting at any
point.  This is the way the old VB mid$ function worked.

def mid(string, start, length):
    # start begins at 0
    if string = "":
        return None
    if start > len(string) - 1:
        start = len(string) - 1
    if length > len(string):
        length = len(string)
    if length < 1:
        length = 1
    return string[start : start + length]

-- 
<Wildman> GNU/Linux user #557453
"The Constitution only gives people the right to
pursue happiness. You have to catch it yourself."
  -Benjamin Franklin



More information about the Python-list mailing list