Working with Strings in Python

Strings in Python are identified as a continuous set of characters represented in the quotation marks.We can access subset of strings using Index [] operator.

Slicing methods:

str = ‘SQLZealots’
print(‘str = ‘, str)

#first character
print(‘str[0] = ‘, str[0])

#last character
print(‘str[-1] = ‘, str[-1])

#slicing 2nd to 5th character
print(‘str[1:5] = ‘, str[1:5])

#slicing 6th to 2nd last character
print(‘str[5:-2] = ‘, str[5:-2])

we have many built in methods with strings. I have listed couple of them and have shown the o/p of each method with an example.

string.upper()           # get all-letters in uppercase
string.lower()           # get all-letters in lowercase
string.capitalize()    # capitalize the first letter
string.title()              # capitalize the first letter of words
string.swapcase()    # converts uppercase and lowercase
string.strip()            # remove all white spaces
string.lstrip()           # removes white space from left
string.rstrip()          # removes white space from right
string.split()             # splitting words
string.split(‘,’)          # split words by comma
string.count(‘l’)       # count how many times l is in the string
string.find(‘Wo’)      # find the word Wo in the string
string.index(“Wo”)  # find the letters Wo in the string
“:”.join(string)          # add a : between every char
” “.join(string)          # add a white space between every char
len(string)                # find the length of the string


Lets write a  small program ,to  extract the Numbers only from a given string .

Code for Extract numbers

You can find the SQL version of the code from here.

Hope you enjoyed the post. Please share your comments .

See also

Introduction to Python

First Program with Python

One thought on “Working with Strings in Python”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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