Substring Printer c-python convertion
Convert a C program that prints the last X characters of a string to equivalent Python code
Understand the Problem
Problem Statement
Convert the provided C code to Python so that the Python program executes successfully and produces the same output as the C version.
The C program reads a string and an integer X, then prints the last X characters of the string using pointer arithmetic.
Constraints
- Input string length is at most 100 characters
- Integer X is positive and less than or equal to string length
- String contains only printable ASCII characters
Examples
Hello World
5WorldThe last 5 characters of 'Hello World' are 'World'
Programming
4mingThe last 4 characters of 'Programming' are 'ming'
test
2stThe last 2 characters of 'test' are 'st'
Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[101];
int len, X;
scanf("%s%n%d", str, &len, &X);
printf("%s", str + len - X);
return 0;
}The C solution uses the %n format specifier in scanf to get the number of characters read into the string, which gives us the length. Then it uses pointer arithmetic (str + len - X) to point to the position X characters from the end of the string, and prints from that position to the end.
Key points:
- %s reads the string
- %n stores the number of characters read so far in len
- %d reads the integer X
- str + len - X creates a pointer to the desired starting position