487,191 views
2 votes
2 votes
Assume the variable myWord references a string. Write a statement that uses a slicing

expression and displays the last 5 characters in the string.
What happens if the myWord is less than 5 characters long?

Please code in python please.

User Andrewrjones
by
2.3k points

1 Answer

23 votes
23 votes

Answer:

"myWord[-5:]"

Step-by-step explanation:

So whenever you slice a string, the syntax in python is expressed as:

string[a:b:c]

where a=start index (this is included in the sliced string)

b = end index (this is excluded from the sliced string)

c = increment

If any of these are included, they are set to default values, where a=0, b=len(string), and c=1.

The increment isn't necessary here, and it's just so you know the syntax a bit more

Anyways, I'm assuming when the question asks to display "the last 5 characters in the string" it means in order? e.g "abcdefghijk" -> "ghijk" and not "abcdefghijk" -> "kjihg"

The last piece of information to know is what a negative index represents.

For example if I have the piece of code

"

string = "hello world"

print(string[-1])

"

This will output "d", and the negative 1 represents the last letter. If you did -2, it would output the 2nd to last letter and so on.

So to print the last 5 characters, we simply use the -5 as the starting index.

"

string = "hello world"

print(string[-5:])

"

This will print "world" or in other words, the last 5 letters. The reason for this is because the -5 in the first spot means the starting index is the 5th to last letter, and when you have the : after the -5, this is the way of telling python you're slicing the string, and not indexing 1 character. You don't need to include another value after that, because it will default to the last index of the string, or more specifically the last index + 1, since the last index is still included.

So the last thing to know, is that if the string isn't greater than 5 characters, it just prints the entire string, and no errors are raised. You can test this out your self as well. So whenever you have a string that's less than 5 characters the entire string is outputted.

User Millsp
by
2.7k points