for example,
extending the string class so that printing it will prepend it with a tab or some white space. Then being able to call it with,
print 'hello world'
Which when seen on the stdout would be prepended with tabs(white space).
for example,
extending the string class so that printing it will prepend it with a tab or some white space. Then being able to call it with,
print 'hello world'
Which when seen on the stdout would be prepended with tabs(white space).
Yes: Edit the source code of Python.
Seriously: Like any other programming model (structured, OO, modeling), Python imposes some limitations on what you can do. While some of those might feel arbitrary or "stupid", there is a good reason for each of them (usually, the drawbacks of all the other solutions or a mistake in the past which can't be fixed anymore without breaking all the existing code).
When you feel that you need to break the rules, take a step back and consider this: Maybe your "solution" is wrong? Maybe there is a better way to achieve what you want?
In this case, use formatting:
f = '\t%s'
print f % 'hello world'
Unlike your solution, this explicitly communicates what you try to achieve.
That said, you can use a technique used "monkey patching." Note that this technique is dangerous. And in most cases, it means that the person using the technique didn't know what they were doing.
Do you want to change the string class, or is it just the behaviour of print
that you want to change? If you:
from __future__ import print_function
(or use Python 3) you can provide your own print
function, for example:
def print(*line, **kwargs):
args = dict(sep=' ', end='\n', file=None)
args.update(kwargs)
sep = args['sep']
end = args['end']
file = args['file']
newlist = [];
for userln in line:
newlist.append("\t"+userln) # prefix the line with a tab
if file == None:
file = sys.stdout
__builtin__.print(sep.join(newlist),end=end,file=file)