Printing specific parts of a string in python

This question already has an answer here:

  • Is there a way to substring a string in Python? 10 answers

  • I'll try to guess expected result:

    def printThree(str):
        for i in range(0, len(str), 3):
            print str[i:i+3]
    

    Output

    >>> printThree("somestring")
    som
    est
    rin
    g
    

    Use slicing:

    def PrintThree(string):
        return string[:3]
    

    This runs as:

    >>> PrintThree('abcde')
    'abc'
    >>> PrintThree('hello there')
    'hel'
    >>> PrintThree('this works!')
    'thi'
    >>> PrintThree('hi')
    'hi'
    >>> 
    

    In the last example, if the length is less than 3, it will print the entire string.

    string[:3] is the same as string[0:3] , in that it gets the first three characters of any string. As this is a one liner, I would avoid calling a function for it, a lot of cuntions gets confusing after some time:

    >>> mystring = 'Hello World!'
    >>> mystring[:3]
    'Hel'
    >>> mystring[0:3]
    'Hel'
    >>> mystring[4:]
    'o World!'
    >>> mystring[4:len(mystring)-1]
    'o World'
    >>> mystring[4:7]
    'o W'
    >>> 
    

    Or, if you want to print every three characters in the string, use the following code:

    >>> def PrintThree(string):
    ...     string = [string[i:i+3] for i in range(0, len(string), 3)]
    ...     for k in string:
    ...             print k
    ... 
    >>> PrintThree('Thisprintseverythreecharacters')
    Thi
    spr
    int
    sev
    ery
    thr
    eec
    har
    act
    ers
    >>> 
    

    This uses list comprehension to split the string for every 3 characters. It then uses a for statement to print each item in the list.

    链接地址: http://www.djcxy.com/p/55114.html

    上一篇: python字符串操作,在字符串中找到一个子字符串

    下一篇: 在Python中打印字符串的特定部分