String is a sequence of characters. In Python, this textual data is handled using str objects.

Python String Methods

In this tutorial, we will learn about some of the String methods in Python like counting occurrences of a sub-string in a string, joining elements of an iterable and returning a string, checking if a string ends with the sub-string, etc.

String Count

str.count() – This python string method counts the number of occurrences of the sub-string, in the string, in the given index range of [start, end]. start and end are optional arguments.

example.py – Python Program

# string
s1 = "Hello World. Hello User."
#sub-string
s2 = "Hello"
#str.count(sub)
count = s1.count(s2)

print(count) #output: 2
Try Online

More examples for str.count.

String Join

str.join() – This python string method accepts an iterable as argument, joins all the items in the iterable and returns the resulting string.

example.py – Python Program

# iterable
list = ['Hello', 'World']
#str.join(iterable)
s1 = str().join(list)

print(s1) #output: HelloWorld
Try Online

More examples for str.join()

String Ends With

str.endswith() – This python string method is used to check if the string ends with the sub-string passed as argument; in the given index range of [start, end], if provided.

example.py – Python Program

#string
s1 = 'Hello World'
#sub-string
s2 = 'rld'
#str.endswith(sub)
b = s1.endswith(s2)

print(b) #output: True
Try Online

More examples for str.endswith()

String Capitalize

str.capitalize() – This python string function returns string with its first character converted to upper case.

example.py – Python Program

#string
s1 = 'hello world'
#capitalize
s2 = s1.capitalize()

print(s2) #output: Hello world
Try Online

More examples for str.capitalize().