Python Cheatsheet: Part II


Since strings are immutable, each function creates a new string as output.

- index('pat') # return ValueError if pat not exist 
- find('pat') # index or -1
x = "junkstringjunk"
print(x.strip("junk")) # o/p = string

String Slicing

x = 'mytestdata'
start = 0
end = 2 # One more than the needed index
step = 1
print(x[start:end:step]) # my
x = 'mytestdata'
print(x[::-1]) # Iterates the string from last (start = 0 + step = (-1))
s = 'astring'
print(s[-1:]) # prints g

# Start from the last and move iterator by negative 1
s = 'astring'
print(s[-1:0:-1]) # reverses the string

Written with StackEdit.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: