Split a date string on a variable character

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Neshotah

    Split a date string on a variable character

    I need to search characters inside a date string so that I can split the string.

    date = '02/03/2010'

    The date separators could be ('/', ' ', '-', '.')
    Last edited by bvdet; Oct 29 '10, 05:03 PM. Reason: Clarify title
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Code:
    >>> possible_characters = ('/', ' ', '-', '.')
    >>> date = '02/03/2010'
    >>> re.split("[%s]" % ("".join(possible_characters)), date)
    ['02', '03', '2010']
    >>>
    Last edited by bvdet; Oct 29 '10, 05:05 PM.

    Comment

    • Neshotah

      #3
      error

      The original result is what I'm looking for, especially if it works no which mix of characters separates the date in the original string. ie. date = '02/03-2010'


      >>> findChar = ('/',' ','-','.',',')
      >>> date = '02/03/2010'
      >>> re.split("[%s]" % ("".join(findCh ar)),date)

      Traceback (most recent call last):
      File "<pyshell#1 5>", line 1, in <module>
      re.split("[%s]" % ("".join(findCh ar)),date)
      NameError: name 're' is not defined


      changed re to date
      >>> date.split('[%s]' % (''.join(findCh ar)),date)

      Traceback (most recent call last):
      File "<pyshell#3 2>", line 1, in <module>
      date.split('[%s]' % (''.join(findCh ar)),date)
      TypeError: an integer is required

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I left out a critical line of code:
        Code:
        import re
        Module re is not built-in.

        Comment

        • Neshotah

          #5
          Thanks for the help, it's working perfectly. Could you explain the details of the re.split line of code? I understand about half of what is going on. I read the help(re), but am still scratching my head wondering how it works.

          Thanks

          Comment

          • Neshotah

            #6
            Is it possible to use ',' as one of the date separators?
            When I add the comma to my list of separators I get an error. Without the comma in the list the program works fine. If I run the dateParts lines from the python shell it separates the comma just fine.

            Traceback (most recent call last):
            File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 112, in <module>
            today = Date(date)
            File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 20, in __init__
            self._date = self.convertDat e() #convert the date to the proper format
            File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 31, in convertDate
            parts = self.dateParts( )
            File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 40, in dateParts
            dateParts = re.split("[%s]" % (''.join(separa tors)),self._da te) #import re for this command to work
            File "C:\Python27\li b\re.py", line 167, in split
            return _compile(patter n, flags).split(st ring, maxsplit)
            File "C:\Python27\li b\re.py", line 245, in _compile
            raise error, v # invalid expression
            error: bad character range
            Code:
            class Date:
                """Class for storing dates"""
            
                MONTHNAMES = ['January', 'February', 'March', 'April',
                'May', 'June', 'July', 'August', 'September', 'October',
                'November', 'December']
            
                MONTHLENGTHS = ['31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31']
                
                def __init__(self, date):
                    '''Constructor'''
                    self._date = date
                    self._date = self.convertDate() #convert the date to the proper format
                            
                def __str__(self):
                    '''Display the date in Month XX, YYYY format'''
                    #pass
                    return self._date
            
            
                def convertDate(self):
                    '''Converts the given date into format Month XX, YYYY format'''
                    #pass
                    parts = self.dateParts()
                    if not parts[0] in Date.MONTHNAMES:
                        parts[0] = Date.MONTHNAMES[int(parts[0])-1]
                    date = parts[0] + ' ' + parts[1] + ', ' + parts[2]
                    return date
            
                def dateParts(self):
                    '''Separates the date into parts: month, day, and year.'''
                    separators = ('/', ' ', '.', '-', ',')
                    dateParts = re.split("[%s]" % (''.join(separators)),self._date) #import re for this command to work
                    return dateParts
            Last edited by bvdet; Oct 30 '10, 11:13 PM. Reason: Please use code tags when posting code. [code]....code goes here....[/code]

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              The re module is used to perform regular-expression pattern matching and replacement in strings. Instead of me trying to explain further, look at this tutorial.

              Reordering the separators seems to work. I don't know why.

              Remember to use code tags!
              Code:
              separators = (',', '/', ' ', '.', '-')

              Comment

              Working...