Re: Checking for valid date input and convert appropriately

2013-02-21 Thread rob . marshall17
The datetime function: strptime() DOES check the date for validity. So try 
something like:

from datetime import datetime

def get_date():
  while True:
try:
  date_in = raw_input("Enter date (dd mm ): ")
  date_out = datetime.strptime(date_in,"%d %m %Y").strftime("%Y-%m-%d")
  return date_out
except ValueError:
  print "Invalid date: {}, try again...".format(date_in)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I Import table from txt file into form letter using Python?

2013-02-21 Thread rob . marshall17
Using the data you supplied as is, you could try something like:

def print_cities(filename):
  # cnt is used just to know if it's time for a newline
  cnt = 0
  cities = open(filename,'r').readlines()
  for city in cities:
# Make sure we have a valid population
if re.match('\d+$',city.split(',')[-1].strip()):
  cnt += 1
  c, p = city.split(',')
  print "{:25} {:15,}".format(c.strip().replace('"',''),int(p.strip())),
  if cnt % 2 == 0: print

Call it this way: print_cities('/path/to/Cities.txt'). The city names need to 
be <= 25 characters in length and the numbers <= 15 characters in length 
including commas but that would give you a number that is bigger than any city 
I know of :-) You can adjust the column sizes as you wish and print the rest of 
the letter formatted around the cities.

Rob
-- 
http://mail.python.org/mailman/listinfo/python-list