Container Data Structures
String Slicing
Slicing ([:]
) is an operation that can be performed on ordered sequential data structures such as lists, tuples, and strings, to retrieve a specific successive portion of the original sequence.
course = " Introduction to Programming"
print(course[1:13])
This first character in a string resides at index 0 and the [1:13]
slice corresponds to the sub-string of the given string starting at index 1 and ending at index 12, excluding the given end index value 13, yielding the substring "Introduction"
. If no start index is specified for the slice, then it is assumed to be 0
, i.e. the beginning index of the string. Similarly if no end-index is specified for the slice, it is assumed to be the length of the string.
course = "Introduction to Programming"
print(course[:12])
generates the output "Introduction"
, and similarly,
course = "Introduction to Programming"
print(course[16:])
produces the output "Programming"
.
The index values used in slicing can be bound to variables:
social_security_id = "25495-456-3224874"
for i in range(5,len(social_security_id)):
print(i*"*" + social_security_id[i:len(social_security_id)])
The code above can be used to hide a certain part of the social security id numbers:
*****-456-3224874
******456-3224874
*******56-3224874
********6-3224874
*********-3224874
**********3224874
***********224874
************24874
*************4874
**************874
***************74
****************4
Try hiding the end or middle portion of the id number such as :
25495-456-322487*
25495-456-32248**
25495-456-3224***
25495-456-322****
25495-456-32*****
or
25495-45*-3224874
25495-4***3224874
25495-*****224874
25495*******24874
2549*********4874
and maybe
*5495-456-322487*
**495-456-32248**
***95-456-3224***
****5-456-322****
*****-456-32*****
******456-3******