Junkie_Monkie
Junkie_Monkie

Reputation: 19

How to add variables together into a new variable where you control the separation

Let's say i've declared three variables which are a date, how can I combine them into a new variable where i can print them in the correct 1/2/03 format by simply printing the new variable name.

month = 1
day = 2
year = 03

date = month, day, year  <<<<< What would this code have to be? 

print(date)

I know i could set the sep='/' argument in the print statement if i call all three variables individually, but this means i can't add addition text into the print statement without it also being separated by a /. therefore i need a single variable i can call.

Upvotes: 2

Views: 224

Answers (4)

dimo414
dimo414

Reputation: 48874

The .join() method does what you want (assuming the input is strings):

>>> '/'.join((month, day, year))
1/2/03

As does all of Python's formatting options, e.g.:

>>> '%s/%s/%s' % (month, day, year)
1/2/03

But date formatting (and working with dates in general) is tricky, and there are existing tools to do it "right", namely the datetime module, see date.strftime().

>>> date = datetime.date(2003, 1, 2)
>>> date.strftime('%m/%d/%y')
'01/02/03'
>>> date.strftime('%-m/%-d/%y')
'1/2/03'

Note the - before the m and the d to suppress leading zeros on the month and date.

Upvotes: 5

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

The correct answer is: use the datetime module:

import datetime

month = 1
day = 2
year = 2003

date = datetime(year, month, day)
print(date)
print(date.strftime("%m/%d/%Y"))

# etc

Trying to handle dates as tuples is just a PITA, so don't waste your time.

Upvotes: 0

rmunn
rmunn

Reputation: 36718

You want to read about the str.format() method:

https://docs.python.org/3/library/stdtypes.html#str.format

Or if you're using Python 2:

https://docs.python.org/2/library/stdtypes.html#str.format

The join() function will also work in this case, but learning about str.format() will be more useful to you in the long run.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118011

You can use the join method. You can also use a list comprehension to format the strings so they are each 2 digits wide.

>>> '/'.join('%02d' % i for i in [month, day, year])
'01/02/03'

Upvotes: 1

Related Questions