user1768884
user1768884

Reputation: 1047

Python won't print out combined string properly

I have a program which has the purpose of combining the first two characters of a string with the last two letters of the string. For example, if you typed in Hello There, you would get Here.

However, when I do this code, only He is printed when I try out Hello There.

def slice_it(string):
"""this bad boy returns the first two chars of a string and the last two charaters of the string. if the string length is less than 4, return an empty string"""

    length = len(string)
    if length < 4:
    return string
    else:
    return string[0:2] + string[0:2:-1]

def main():
    string = raw_input("Give us a phrase or a word please: ")
    string = slice_it(string)
    print string

if __name__ == '__main__':
    main()

Upvotes: 0

Views: 127

Answers (1)

David Robinson
David Robinson

Reputation: 78620

Change the line

return string[0:2] + string[0:2:-1]

to

return string[0:2] + string[-2:]

string[0:2:-1] doesn't get the last two characters of the string (indeed, it doesn't get anything).

Upvotes: 3

Related Questions