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. – Python Program

# string
s1 = "Hello World. Hello User."
s2 = "Hello"
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. – Python Program

# iterable
list = ['Hello', 'World']
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. – Python Program

s1 = 'Hello World'
s2 = 'rld'
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. – Python Program

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

print(s2) #output: Hello world
Try Online

More examples for str.capitalize().