marryd
marryd

Reputation:

Format in Python

I have a list of values as follows:

no column
1. 111-222-11
2. 112-333-12
3. 113-444-13

I want to format the value from 111-222-11 to 111-222-011 and format the other values similarly. Here is my code snippet in Python 3, which I am trying to use for that:

‘{:03}-{:06}-{:03}.format(column)

I hope that you can help.

Upvotes: 0

Views: 28

Answers (1)

Roman Riabenko
Roman Riabenko

Reputation: 261

Assuming that column is a variable that can be assigned string values 111-222-11, 112-333-12, 113-444-13 and so on, which you want to change to 111-222-011, 112-333-012, 113-444-013 and so on, it appears that you tried to use a combination of slice notation and format method to achieve this.

Slice notation

Slice notation, when applied to a string, treats it as a list-like object consisting of characters. The positional index of a character from the beginning of the string starts from zero. The positional index of a character from the end of the string starts with -1. The first colon : separates the beginning and the end of a slice. The end of the slice is not included into it, unlike its beginning. You indicate slices as you would indicate indexes of items in a list by using square brackets:

'111-222-11'[0:8]

would return

'111-222-'

Usually, the indexes of the first and the last characters of the string are skipped and implied by the colon.

Knowing the exact position where you need to add a leading zero before the last two digits of a string assigned to column, you could do it just with slice notation:

column[:8] + '0' + column[-2:]

format method

The format method is a string formatting method. So, you want to use single quotes or double quotes around your strings to indicate them when applying that method to them:

'your output string here'.format('your input string here')

The numbers in the curly brackets are not slices. They are placeholders, where the strings, which are passed to the format method, are inserted. So, combining slices and format method, you could add a leading zero before the last two digits of a column string like this:

'{0}0{1}'.format(column[:8], column[-2:])

Making more slices is not necessary because there is only one place where you want to insert a character.

split method

An alternative to slicing would be using split method to split the string by a delimiter. The split method returns a list of strings. You need to prefix it with * operator to unpack the arguments from the list before passing them to the format method. Otherwise, the whole list will be passed to the first placeholder.

'{0}-{1}-0{2}'.format(*column.split('-'))

It splits the string into a list treating - as the separator and puts each item into a new string, which adds 0 character before the last one.

Upvotes: 2

Related Questions