Output first 100 characters in a string

print my_string[0:100]

From python tutorial:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So it is safe to use x[:100].


Easy:

print mystring[:100]

To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too

>>> greek=u"αβγδεζηθικλμνξοπρςστυφχψω"
>>> print len(greek)
25
>>> print greek[:10]
αβγδεζηθικ

If you want to run the above code as a script, put this line at the top

# -*- coding: utf-8 -*-

If your editor doesn't save in utf-8, substitute the correct encoding


Slicing of arrays is done with [first:last+1].

One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:

if len(s) <= 100:
    print s
else:
    print "%s..."%(s[:97])

And yes, I know () is superfluous in this case for the % formatting operator, it's just my style.