String Variables: Printing individual characters

Hello,

How to print last 3 (say) characters of a string?

My query:
If printing first 3(say) characters is-
name = “Python”
print(name[0:3])

AND printing last character is-
name = “Python”
print(name[-1])

Then for last 3 characters in Reverse order-
name = “Python”
print(name[-1:-3])

BUT, apparently it does not work like that.
Output shows simply a blank line.

This should print the last three:

print(name[-3:])

And if I wanted to reverse those then you can use a negative step:

print(name[-1:-3:-1])

I have not tested that syntax (just going from memory), so I am just making sure you know what could be done.

Hello,

Thank you for replying.
I tried running this code but it does not work.
Returns same blank line as the code I mentioned for my query.

Any other ideas?
I have just started with ‘Python Mastery’ course by Code with Mosh

This should work:

name = "Python"

print(name[-3:])

When I run this it returns:

hon

Thank you for replying.

I want to print it is reverse.
EXAMPLE-
name =“hello”
Output desired = olleh

Sorry for misunderstanding the question. To reverse the string you can use:

name = "Python"

reverse = name[::-1]
print(reverse[-3:])

name = "Python"
print((name[::-1])[-3:])

both ways return
‘tyP’

1 Like

Hello,

Thanks for providing the solution.
Seems like a ‘reverse’ is new function which I’m yet to learn.

Will you kindly explain the 2nd method? This one seems to be related to the simple print() that was taught in the course so far.

It is not a new function, it is a variable that @Manj_P assigned earlier using the step syntax to reverse the string:

That syntax says take the whole string and use a step of -1 to get each character in reverse order. People sometimes define this as a function to help simplify their code:

def reverse(input):
  return input[::-1]

Which can then be used to achieve your desired result AFAICT:

reverse(name[-3:])

@Manj_P is just doing all of the work inline here rather than extracting the helper variable reverse. There are extra parentheses here which may be confusing to read which is why the helper variable or function version is more readable.

1 Like