bzal
bzal

Reputation: 203

what is this special kind of character?

I've been following a python 3 book and have been learning to program on my own but the book doesn't explain this particularly:

print(end = "%2i" % column)

I empirically found out that they replace the value outside with inside, but I'd like to be specific about this. I would have liked to Google it up before resolving here but I don't even know what is it called and are there any other expressions like these what are these called?

Upvotes: 1

Views: 822

Answers (1)

Jared Goguen
Jared Goguen

Reputation: 9010

There are a few things going on here. First, let's look at the string:

'%2i' % column

In this string, the % indicates that a value can be substituted in that location in the string. The 2 indicates that the substitution will be at least 2 characters wide. The i indicates that an integer should be passed as the formatting argument. Then, the % column part indicates that the integer column should be substituted in for %2i per the rules described above. Here are some examples:

'%2i' % 4  # ' 4'
'%2i' % 12 # '12'
'%3i' % 12 # ' 12'
'%s: %s' % ('a', 'b') # 'a: b'

The final example shows that multiple values can be substituted in. All this being said, using % for string formatting is not recommended; instead str.format is preferred.

'{}: {}'.format('a', 'b') # 'a: b'

Both these methods are relatively intuitive and you can Google "string formatting Python" if you want to know more.

Now, let's look at the print(end='...') part of the statement. The print function takes an argument called end which specifies the string to be printed after whatever else you printed. The default value is end='\n'. This produces natural behavior if you call print a few times in a row as each thing will be printed on a new line.

print('a')
print('b')
print('c')

# a
# b
# c

However, if you want to print multiple things that are not separated by new lines, you can provide the function and argument for end.

print('a', end=', ')
print('b', end=', ')
print('c', end='...\n')
print('There we go!')

# a, b, c...
# There we go!

Upvotes: 3

Related Questions