substring python

Posted by w3diy - 5 months ago

Know about Substring in Python

string = "w3diyfreedownloadsourceCode"
print(string[0:5])

Get a substring of length 4 from the 3rd character of the string

string = "w3diyfreedownloadsourceCode"
print(string[2:6])

Get the last character of the string

string = "w3diyfreedownloadsourceCode"
print(string[-1])

Get the last 5 characters of a string

string = "w3diyfreedownloadsourceCode"
print(string[-5:])

Get a substring which contains all characters except the last 4 characters and the 1st character

string = "w3diyfreedownloadsourceCode"
print(string[1:-4])

OR

str = w3diyfreedownloadsourceCode

print str[-5:-2] # prints ‘eCa’
print str[-1:-2] # prints ‘’ (empty string)

Get every other character from a string

string = "w3diyfreedownloadsourceCode"
print(string[::2])