Home > Mobile >  Python: Taking end 3 characters in a string from a user input
Python: Taking end 3 characters in a string from a user input

Time:06-07

I have an algorithm which I want to run in Python. It wants me to get 2 inputs from the user, then extract the last 3 letters of each input, then output these 2 sets of extracted characters side by side. I know how to extract end characters from a given array but am struggling to work out the correct syntax for extracting end characters from a user input.

Got as far as...

fname = input("What is your firstname? ")
flength = len(fname)
sname = input("What is your surname? ")
slength = len(sname)

...understanding that I need to know the length of the input to find the last 3 characters of it...

for x in range(flength):print(flength)

...then tested the loop runs for the exact length of the input, so far so good, but the next syntax I would usually use are ones for an array. Can an input be converted into an array perhaps? Is there an easier way to achieve this I am overlooking?

Thanks!

CodePudding user response:

You don't need to know the length, nor use a loop, use the slicing notation on strings str[start:end:step]

Along with negative indices, to start from end

fname = input("What is your firstname? ")
sname = input("What is your surname? ")
print(fname[-3:])
print(sname[-3:])
What is your firstname? johnny
What is your surname? Philivitch
nny
tch

CodePudding user response:

Use the slicing operation [-3:] to get the last three characters (-3 in a slice means "three characters from the end"):

>>> print(input("What is your firstname? ")[-3:], input("What is your surname? ")[-3:])
What is your firstname? Daniel
What is your surname? Gough
iel ugh
  • Related