the str.split(sep,maxsplit) function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • david2031
    New Member
    • Oct 2011
    • 4

    the str.split(sep,maxsplit) function

    given:
    my = 'my name is david'

    i would like to make this into a list with 2 values
    i would like the list to be:
    mylist = ['my name is','david']

    so i try using:
    mylist = my.split(' ',1)

    but i soon find it splits left to right which returns:
    mylist = ['my','name is david']

    to avoid having to use alot of other code, i am wondering if there is a way to make it split right to left or reverse of the way its splitting?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Following are a couple of ways, but each requires additional code.
    Code:
    >>> s = 'my name is david'
    >>> s.split()
    ['my', 'name', 'is', 'david']
    >>> s1 = 'my david'
    >>> s2 = 'david'
    >>> def split_once_rightmost(s):
    ... 	seq = s.split()
    ... 	if len(seq) > 1:
    ... 		return [" ".join(seq[0:-1]), seq[-1]]
    ... 	return seq
    ... 
    >>> split_once_rightmost(s)
    ['my name is', 'david']
    >>> split_once_rightmost(s1)
    ['my', 'david']
    >>> split_once_rightmost(s2)
    ['david']
    >>> seq = s.replace(" ", "***", s.count(" ")-1).split(" ")
    >>> seq[0] = seq[0].replace("***", " ")
    >>> seq
    ['my name is', 'david']
    >>>

    Comment

    • basilho
      New Member
      • Oct 2011
      • 1

      #3
      Code:
      >>> my = 'my name is david'
      >>> import re
      >>> re.findall('(.*)\s(.*)', my)
      [('my name is', 'david')]
      or
      Code:
      >>> my
      'my name is david'
      >>> lst = my.split(' ')
      >>> lst
      ['my', 'name', 'is', 'david']
      >>> result = []
      >>> result.append(' '.join(lst[:-1]))
      >>> result.append(lst[-1])
      >>> result
      ['my name is', 'david']

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I knew there would be a re solution. Thanks for posting basilho. You can use match object method group to create the OP's mylist.
        Code:
        >>> my = 'my name is david'
        >>> import re
        >>> patt = re.compile('(.*)\s(.*)')
        >>> m = patt.match(my)
        >>> [m.group(1), m.group(2)]
        ['my name is', 'david']
        >>>

        Comment

        • papin
          New Member
          • Nov 2011
          • 7

          #5
          The very basics of lists:
          Code:
          >>> my = my.split()
          >>> print (' '.join(my[:-1]), my[-1])
          ('my name is', 'david')

          Comment

          Working...