Quick links: C-Tricks HR Interview Que. Code Snippets C Programs C++ Programs Java Programs PHP Examples

Home » Python

Python String Methods with Examples (Set-2)

String methods in Python (Set 2) : Here we will learn about predefined methods of String in Python with Examples and Explanations.
Submitted by Shubham Singh Rajawat, on August 08, 2017

1. len(str)

This function will return the length of the string(str) given as argument.

2. lstrip([chars])

This method will remove all the characters specified from the left of the string.
Here,
chars it contains all the characters, by default space.

3. rstrip([chars])

This method will remove all the characters specified from the right of the string.
Here,
chars it contains all the characters, by default space.

Example: #Program to implement above methods

string="Includehelp is a portal to Learn Concepts"
print('Length of string is',len(string))
print(string.lstrip('Isctn'))
print(string.rstrip('Instpc'))

Output

Length of string is 41
ludehelp is a portal to Learn Concepts
Includehelp is a portal to Learn Conce  

4. str.join(sequence)

This method will return a string, which is the concatenation of the strings in 'sequence' by the separator 'str'.
Here,
sequence sequence- this the sequence of elements to be joined.

Example: #Program to implement join

str=' '
l=('Include','help','is','a','portal','to','learn')
print(str.join(l))
str='_'
l=('Include','help')
print(str.join(l))

Output

Include help is a portal to learn
Include_help

5. isalpha()

returns true if string only contains alphabets else return false.

6. isalnum()

returns true if the string is combination of alphabets and numbers only else return false.

Example: #Program to implement above methods

string="Includehelp"
string1="Include help"
string2='123456'
string3='12345Hii'
print(string.isalpha())
print(string1.isalpha())  #It will return False as string1 contains a space
print(string2.isalnum())
print(string3.isalnum())

Output

True
False
True
True

7.count(str,beg,end)

This method will count the occurrence of the substring between specified indices.

Here,
str - substring to be count. beg - it is the beginning index, by default 0. end - it is the end index, by default string length.

Example: #Program to implement count

string="Includehelp is a portal to Learn Concepts"
print(string.count('a'))

Output

3


Sponsored Links






COMMENTS