Given the string as an input to the Python program, and also the value of n as to extract first n characters from a given string you have to print the first n characters out of the given string.
let's try to solve this using a python code
Write A Python Program To Extract The First N Characters Of A String
Let's take a variable named as text and use the input function call and ask the user to enter a string. take another variable name as n using the input function call and ask the user to enter the value of an to extract the first n characters from a given string and then convert into integer using the type conversion.
text = input("Enter a String : ")
N = int(input("Enter Value of N : "))
Now using the if statement check if the value of n is less than 0. if the value of an is less than 0 then print invalid Value of n using the print function call
Now using the else block print user friendly message. Now take another variable as new_text and use the string slicing method to remove the last n characters using [:N] to extract the first N characters of a given string.
Finally print the new_text variable.
if N < 0:
print("Value of N is Invalid")
else:
print(f"The First {N} Characters Of A String")
new_text = text[:N]
print(new_text)
Python code
====================
text = input("Enter a String : ")
N = int(input("Enter Value of N : "))
if N < 0:
print("Value of N is Invalid")
else:
print(f"The First {N} Characters Of A String")
new_text = text[:N]
print(new_text)
Output
===============
Enter a String : hello python
Enter Value of N : 4
The First 4 Characters Of A String
hell
Output
================
Enter a String : code with tj
Enter Value of N : -23
Value of N is Invalid
Output
================
Enter a String : code with tj
Enter Value of N : 6
The First 6 Characters Of A String
code w
Conclusion
===============
Try executing the above Python program by providing random string and integer value as an Input and then evaluate the result.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments