Python Forum

Full Version: Standard library code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi people,

I was just checking out some code from the standard library from python 3.6.1. This specific piece of code is ftplib.py and is meant to replace some piece of a string. From the function I understand the string should be something like "pass yourpasswordhere". Every letter from "yourpasswordhere" should be replaced with an *, pretty clear. Only thing I wonder about is what's the reason for the s[i:] in the and at the last s = statement? Seems to me it has no function? Thank you for reading :)

    # Internal: "sanitize" a string for printing
    def sanitize(self, s):
        if s[:5] in {'pass ', 'PASS '}:
            i = len(s.rstrip('\r\n'))
            s = s[:5] + '*'*(i-5) + s[i:]
        return repr(s)
The i variable is the length of the string after terminal line feeds and carriage returns are taken out. So the s assignment on line 5 combines three things: the first five characters of the original s, a number of asterisks (*) equal to the length of the original s (not counting the first five characters or any terminal LF/CR), and any terminal LF or CR from the original s. It's a way of preserving those terminal characters, if they exist.
Just an FYI, you might like Doug Helmann's site: https://pymotw.com/3/ (python 3) or https://pymotw.com/2/ (python 2)