'Reverse last X characters

strVal = input().strip()
X = int(input())
print(-1:X-1:-1)

The program must accept a string S and an integer X as the input. The program must print the last X characters of S in reverse order as the output. As the Problem is what that it runs some of the string and doesnt run some of string.Could anyone tell me whats wrong in this code..did I miss something?

Examples:

  1. For String: baseBall, and input: 4, Output = llab
  2. For String: olympics, and input: 7, Output = scipmyl


Solution 1:[1]

print(strVal[-1:-1-X:-1])

You need to print the slice of strVal. Not just the indexes.

I also changed the indexes to get the right result.

Solution 2:[2]

print(strVal[-X:][::-1])

First we are getting the last X characters in reverse order, then we are reversing the required part. This is better than understanding indexing for beginners.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Roub
Solution 2 Paul Roub