Python Tutorial | Python Strings

Python String Built-in functions/Methods

Python String inbuilt Methods

Python has a set of built-in methods that you can use on strings

capitalize()

The capitalize() method returns a string where the first character is upper case.
Syntax
string.capitalize()
Upper case the first letter in this sentence:

txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
txt = "7 is lucky number"
x = txt.capitalize()
print (x)

output:

Hello, and welcome to my world.
7 is lucky number

casefold()

The casefold() method returns a string where all the characters are lower case.
This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case, and will find more matches when comparing two strings and both are converted using the casefold() method.
Syntax
string.casefold()
Make the string lower case:

txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)

output:

hello, and welcome to my world!

center()

The center() method will center align the string, using a specified character (space is default) as the fill character.
Syntax
string.center(length, character)

length : The length of the returned string
character :The character to fill the missing space on each side. Default is ” ” (space)(Optional)

Using the letter “*” as the padding character:

txt = "catalyst"
x = txt.center(20, "*")
print(x)

output:

******catalyst******

count()

The count() method returns the number of times a specified value appears in the string.
Syntax
string.count(value, start, end)
value : A String. The string to value to search for (Required)
start : An Integer. The position to start the search. Default is 0 (Optional)
end : An Integer. The position to end the search. Default is the end of the string(Optional).
Example
Return the number of times the value “apple” appears in the string:
n = “I love apples, apple are my favourite fruit”

n = "I love apples, apple are my favourite fruit"
x = n.count("apple")
print(x)

Output:

2

Example

Search from position 10 to 24:
txt = “I love apples, apple are my favorite fruit”

txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple", 10, 24)
print(x)

Output:

1

endswith()

The endswith() method returns True if the string ends with the specified value, otherwise False.
Syntax
string.endswith(value, start, end)
value : The value to check if the string ends with (Required)
start : An Integer specifying at which position to start the search (Optional)
end : An Integer specifying at which position to end the search(Optional)

Example
#Check if the string ends with a punctuation sign (.):

txt = "Hello, welcome to my world."
x = txt.endswith(".")
print(x)

Output:

true

Example
Check if the string ends with the phrase “my world.”:

txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)

Output:

true

Example
Check if position 5 to 11 ends with the phrase “my world.”:

txt = "Hello, welcome to my world."
x = txt.endswith("my world.", 5, 11)
print(x)

Output:

false

expandtabs()

The expandtabsize() method sets the tab size to the specified number of whitespaces.
Syntax
string.exandtabs(tabsize)

tabsize : A number specifying the tabsize. Default tabsize is 8 (Optional)
Example
Set the tab size to 2 whitespaces:

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(2)
print(x)

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(5)
print(x)

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(10)
print(x)

find()

The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.

Syntax
string.find(value, start, end)

value: Required. The value to search for
start: Optional. Where to start the search. Default is 0
end: Optional. Where to end the search. Default is to the end of the string

Example
Where in the text is the word “welcome”?:

txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)

Output:
7
(Counting starts from 0)

Example
Where in the text is the first occurrence of the letter “e”?:

txt = "Hello, welcome to my world."
x = txt.find("e")
print(x)

Output:

1

isalnum()

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.

Syntax
string.isalnum()

Example
Check if all the characters in the text are alphanumeric:

txt = "Company12"
x = txt.isalnum()
print(x)
txt = "Company@12"
x = txt.isalnum()
print(x)

Output:

true
false

Example
Check if all the characters in the text is alphanumeric:

txt = "Company 12"
x = txt.isalnum()
print(x)

Output:

false

isalpha()

The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.

Syntax
string.isalpha()
Check if all the characters in the text are letters:

#1
txt = "CompanyX"
x = txt.isalpha()
print(x) 
#2
txt = "Company10"
x = txt.isalpha()
print(x)

Output:

true
false

isdecimal()

The isdecimal() method returns True if all the characters are decimals (0-9).
Syntax
string.isdecimal()
Example
Check if all the characters in the unicode object are decimals:

txt = "\u0033" #unicode for 3
x = txt.isdecimal()
print(x) 
a = "\u0030" #unicode for 0
b = "\u0047" #unicode for G
print(a.isdecimal())
print(b.isdecimal())

Output:

True
True
False

isdigit()

The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.

Syntax
string.isdigit()
Example
Check if all the characters in the text are digits:

txt = "50800"
x = txt.isdigit()
print(x)

txt = "50800A"
x = txt.isdigit()
print(x)
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²

print(a.isdigit())
print(b.isdigit())

Output:

True
False
True
True
>>>

islower()

The islower() method returns True if all the characters are in lower case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax
string.islower()
Example
Check if all the characters in the text are in lower case:

txt = "hello world!"
x = txt.islower()
print(x)
a = "Hello world!"
b = "hello 123"
c = "mynameisMohit"

print(a.islower())
print(b.islower())
print(c.islower())

Output:

True
False
True
False

istitle()

The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.
Symbols and numbers are ignored.

Syntax
string.istitle()
Example
Check if each word start with an upper case letter:

txt = "Hello, And Welcome To My World!"
x = txt.istitle()
print(x) 
a = "HELLO, AND WELCOME TO MY WORLD"
b = "Hello"
c = "22 Names"
d = "This Is %'!?"
print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())

Output:

True
False
True
True
True
>>>

isupper()

The isupper() method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax
string.isupper()
Example
Check if all the characters in the text are in upper case:

txt = "THIS IS NOW!"
x = txt.isupper()
print(x) 
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS MOHIT"
print(a.isupper())
print(b.isupper())
print(c.isupper())

Output:

True
False
False
True
>>>

join()

The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.

Syntax
string.join(iterable)

iterable: Required. Any iterable object where all the returned values are strings

#Example
Join all items in a tuple into a string, using a hash character as separator:

#Example
Join all items in a dictionary into a string, using a the word “TEST” as separator:

myTuple = ("Johny", "Pinku", "Vicky")
x = "#".join(myTuple)
print(x) 

myDict = {"name": "Johny", "country": "India"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)

Output:

Johny#Pinku#Vicky
nameTESTcountry
>>>

swapcase()

The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax
string.swapcase()
Example
Make the lower case letters upper case and the upper case letters lower case:

txt = "Hello My Name Is MOhit"
x = txt.swapcase()
print(x) 

Output:

hELLO mY nAME iS moHIT
>>>

title()

The title() method returns a string where the first character in every word is upper case. Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Syntax
string.title()
Example
Make the first letter in each word upper case:

txt = "Welcome to my world"
x = txt.title()
print(x) 
txt = "Welcome to my 2nd world"
x = txt.title()
print(x) 

Output:

Welcome To My World
Welcome To My 2Nd World
>>>

Example
Note that the first letter after a non-alphabet letter is converted into a upper case letter:

txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x)

Output:

Hello B2B2B2 And 3G3G3G

upper()

The upper() method returns a string where all characters are in upper case. Symbols and Numbers are ignored.

Syntax
string.upper()
Example
Upper case the string:

txt = "Hello my friends"
x = txt.upper()
print(x) 

Output:

HELLO MY FRIENDS
>>>

format()

The format() method formats the specified value(s) and insert them inside the string’s placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.
The format() method returns the formatted string.

Syntax
string.format(value1, value2…)
value1, value2… Required. One or more values that should be formatted and inserted in the string. The values can be A number specifying the position of the element you want to remove.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The values can be of any data type.

The Placeholders

The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.

Example
Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:

txt = “For only {price:.2f} dollars!”
print(txt.format(price = 49))

Example
Using different placeholder values:
txt1 = “My name is {fname}, I’am {age}”.format(fname = “Amit”, age = 16)
txt2 = “My name is {0}, I’am {1}”.format(“Amit”,16)
txt3 = “My name is {}, I’am {}”.format(“Amit”,16)

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49)) 

#Using different placeholder values:
txt1 = "My name is {fname}, I'am {age}".format(fname = "Amit", age = 16)
txt2 = "My name is {0}, I'am {1}".format("Amit",16)
txt3 = "My name is {}, I'am {}".format("Amit",16) 
print(txt1)
print(txt2)
print(txt3)

Output:

For only 49.00 dollars!
My name is Amit, I’am 16
My name is Amit, I’am 16
My name is Amit, I’am 16
>>>

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling

Visitor Counter

0183261