Monday, October 28, 2019

Python tutorial 9 | string methods

Let us continue with Python Tutorials for Beginners. If you are new to Python strings, please see my Python tutorial 2 | Handling Strings first. This Python beginner tutorial explains many useful Python string functions with examples. Please view the Python video tutorial 9 or read on...

Now let us see Python examples of string methods in Python programming.

# Python code example
greeting = "Hello"

# print in lower case
print (greeting.lower())

# print in upper case
print (greeting.upper())

name = 'john doe'
# print only the first character in capitals with capitalize
print (name.capitalize())

# print the first character capitalized in every word with title
print (name.title())

# Python code example
some_string = "   this is some text   "
# strip the left hand side spaces with lstrip
print (some_string.lstrip())
# strip the given left hand side characters i.e. spaces, t and h with lstrip
print (some_string.lstrip(' th'))
# strip the right hand side spaces with rstrip
print (some_string.rstrip())
# strip the given right hand side characters i.e. t and spaces with rstrip
print (some_string.rstrip('t '))
# strip spaces on both ends with strip
print (some_string.strip())

# Python code example
job = "developer"
# count the number of given characters, e in this example
print (job.count('e')) # return 3 because there are 3 e's in "developer"

# find one string within another string, "er " in this example
# print 7 because a Python string's index starts with 0
print (job.find("er"))

# get the suffix of a string with endswith method
print (job.endswith('er')) # return True

# know if all characters in the string are lower case with islower method
print (job.islower()) # return True

# know if all the characters in the string are upper case with isupper method
print (job.isupper()) # return False

# replace a part of the string with replace method
name = "Jane Doe"
print(name.replace ("Doe", "Smith")) # print Jane Smith

Want to learn these string methods in detail and see the Python samples working? View my Python video tutorial 9. Thank you.


  1. Thanks for sharing such a informative post with us, keep sharing-ZuZucodes INC

  2. Nice post, thanks for sharing this informative post. Keep on posting.
    Java Training in Mohali

  3. Hey! This is my first visit to your blog! We are
    a collection of volunteers and starting
    a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!

    Software consultant Company Frisco USA

    Node js Development Company Texas USA

    Sales Tracking Development Company Texas USA