Python string method example

String and text is the data we read on user interface, in programming we often need to manipulate string for various reasons, In this tutorial you will learn python string methods, there are many in-built string functions in python.

String concatenation, adding two string or string variable! suppose we want to add two string and write in next line

var1 ="value1"
var2="value2"
print(var1 + var2)

#or if you want to write in a file next line 

file.write(f"{var1+var2}\n") 

Multiline string in Python Example

Before we start with some string methods example, let’s understand how we can write string in Python.

# Creating a multiline string
multiline_str = """ We are learning Python.
At WebTrainingRoom.Com.
Best place to learn python programming with examples."""
print("Multiline string: \n" + multiline_str)

We can also create multiline string in python code and append new values, the example below will be very useful for forming SQL string with different values, notice here we have used in-built format method.

sql_query1="update tbStudent set firstName='{}', LastName='{}', RegDate='{}', email='{}' where StuId={}";
sql_query1 =sql_query1.format(student.first_name, student.last_name, today, student.Email, student.StuId); 

string functions in python code

Here are some commonly used built-in string functions in python with example

  1. upper() : Convert all characters of a string into upper case, Oppositely we can user lower() function
    message = "hello, and welcome to my home.";
    print (message.upper())
    # result: Hello, welcome to my home.
    
  2. capitalize() : Convert first character of a string to upper case
    message = "hello, and welcome to my home.";
    print (message.capitalize())
    # result: HELLO, AND WELCOME TO MY HOME.
    
  3. replace("old-value","new-value") : Replace old value with new value within a string
    message = "hello, and welcome to my home.";
    print (message.replace("home","study room"))
    # result: hello, and welcome to my study room.
    
  4. split() : Split a string into comma separated array. you can also use rsplit(", ") function, if you want to specify separator
    message = "hello, and welcome to my home.";
    print (message.split())
    # result: ['hello,', 'and', 'welcome', 'to', 'my', 'home.']
    
  5. rfind("value"): finds the last occurrence of the specified value. the method returns -1 if no matching value found.
    message = "hello, and welcome to my home.";
    print (message.rfind("home"))
    # result: 25
    
  6. startswith() : Check if a string starts with a specified character or word
    message = "hello, and welcome to my home.";
    print (message.startswith("hello"))
    # result: True
    
  7. endswith() : Check if a string ends with a specified character or word
    message = "hello, and welcome to my home.";
    print (message.startswith("home"))
    # result: True
    
  8. strip() : Remove all spaces from both side of the string, this is just like trim function in other programming language
    message = " hello, and welcome to my home. ";
    print (message.strip())
    # result: True
    

    rstrip(): Remove all spaces from right side of a string.

    lstrip(): Remove all spaces from left side of a string.

  9. reversed() : This method returns an iterator that accesses the given sequence in the reverse order.
    message = "WebTrainingRoom";
    print (list(reversed(message)))
    # result: ['m', 'o', 'o', 'R', 'g', 'n', 'i', 'n', 'i', 'a', 'r', 'T', 'b', 'e', 'W']
    

    We can also use range with reversed() function in python

    seqRange = range(3, 6)
    print (list(reversed(seqRange)))
    # result: [5, 4, 3]
    

    Or with a list

    seqList = [1, 2, 4, 3, 5]
    print (list(reversed(seqList)))
    
  10. slice() returns a slice object used to slice a sequence, for example we can get substring of any given string using slice object
    myString = "Python"
    sliceObj = slice(3)
    print(myString[sliceObj])
    

    We also can write like example below

    myString = "Python"
    sliceObj = slice(2, 4, 6)
    print(myString[sliceObj])
    

Above python string functions will help you to manipulate any string values in python code, but if you want to read text (type of string) from any file, then you need to use file object in python programming.

 
Python string methods
Learn python programming with free python coding tutorials.
Other Popular Tutorials
Python string function examples
Python programming examples | Join Python Course