Junior — Middle
What happens to the content of a string in Python if we use a slicing operation to shorten it?
sobes.tech AI
Answer from AI
In Python, strings are immutable. When you use a slice operation on a string, for example s = s[:5], a new string is created containing the specified slice, and the original string remains unchanged.
This means that the slice operation does not modify the original string, but returns a new one. If you assign the result back to a variable, it will refer to the new string.
Example:
s = "Example string"
s2 = s[:6] # 'Example'
print(s) # 'Example string'
print(s2) # 'Example'
s = s[:6] # now s points to the new string
print(s) # 'Example'
Thus, slices in Python do not modify the original string, but create new objects.