Saturday, February 22, 2020

Python String isnumeric() Method

The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not.

isnumeric() method returns true if all characters in the string are numeric characters and there is at least one character, false otherwise. Numeric characters include digits (0..9) and all characters that have the Unicode numeric value property like superscripts or subscripts (as example 26 and 42), fractions like ¼.

Python isnumeric method examples

1. Using isnumeric() method to check if all the characters are digits or not.

str = '345'
print(str)
print(str.isnumeric())

str = 'A12B'
print(str)
print(str.isnumeric())

Output

345
True
A12B
False

2. Using isnumeric() method with superscripts or subscripts. For such strings isnumeric() method returns true.

str = '2\u2076'
print(str)
print(str.isnumeric())

str = '4\u2082'
print(str)
print(str.isnumeric())

Output

26
True
42
True

3. Using isnumeric() method with characters that have Unicode numeric value property.

s = '\u246D' #CIRCLED NUMBER FOURTEEN ?
print(s)
print(s.isnumeric())

s = '\u2474' #PARENTHESIZED DIGIT ONE ?
print(s)
print(s.isnumeric())

s = '\u248C' # DIGIT FIVE FULL STOP ?
print(s)
print(s.isnumeric())

s = '\u24B0' #PARENTHESIZED LATIN SMALL LETTER U ?
print(s)
print(s.isnumeric())

Output

⑭
True
⑴
True
⒌
True
⒰
False

That's all for this topic Python String isnumeric() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String isdigit() Method
  2. Changing String Case in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Abstract Class in Python
  5. Global Keyword in Python With Examples

You may also like-

  1. Python assert Statement
  2. Interface in Python
  3. Python Exception Handling - try,except,finally
  4. Convert String to int in Python
  5. Java Multithreading Tutorial
  6. String in Java Tutorial
  7. Spring Web MVC Tutorial
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Thursday, February 20, 2020

Python String isdigit() Method

The isdigit() method in Python String class is used to check if all the characters in the string are digits or not.

isdigit() method returns true if all characters in the string are digits and there is at least one character, false otherwise. This method works for only positive, unsigned integers and for superscripts or subscripts which are passed as unicode character.

Python isdigit method examples

1. Using isdigit() method to check if all the characters are digits or not.

str = '456'
print(str)
print(str.isdigit())

str = 'A12'
print(str)
print(str.isdigit())

Output

456
True
A12
False

2. Using isdigit() method with superscripts or subscripts. For such strings isdigit() method returns true.

str = '2\u2076'
print(str)
print(str.isdigit())

str = '4\u2082'
print(str)
print(str.isdigit())

Output

26
True
42
True

3. Using isdigit() method with negative numbers or decimal numbers. For such strings isdigit() method returns false.

str = '2.45'
print(str)
print(str.isdigit())

str = '-12'
print(str)
print(str.isdigit())

Output

2.45
False
-12
False

4- To check negative numbers or decimal numbers using Python isdigit() method, you need to remove the minus or a decimal character before checking.

Using lstrip() method you can remove the specified leading characters (used to remove ‘-’ sign here).

Using replace() method you can replace decimal character (replace decimal with no space here).

str = '-12'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '2.45'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '-0.657'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

Output

True
-12
True
2.45
True
-0.657

Since String is immutable in Python so the original string remains unchanged.

That's all for this topic Python String isdigit() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. Python String join() Method
  4. Namespace And Variable Scope in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Python Program to Find Factorial of a Number
  2. Operator Overloading in Python
  3. Abstraction in Python
  4. Volatile Keyword in Java With Examples
  5. Invoke Method at Runtime Using Java Reflection API
  6. Setting And Getting Thread Name And Thread ID - Java Program
  7. Dependency Injection Using factory-method in Spring
  8. HDFS Commands Reference List

Wednesday, February 19, 2020

Check String Empty or Not in Python

If you need to check if a String is empty or not in Python then you have the following options.

Using len() function to check if String is empty

You can check length of String in Python using len() function. If String is of length zero that means it is an empty string. Here note that String with only whitespaces is considered a non-zero length string, if you want to evaluate such string also as empty string then use strip() method to strip spaces before checking the length of the String.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3

As you can see str2 which is a String with whitespaces is not a length zero String so not considered empty. You need to strip whitespaces for such strings.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string.strip()) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3
empty String

Using not to check if String is empty

An empty String is considered false in boolean context so using not string you can find whether the String is empty or not. Here note that String with only whitespaces is not considered false so you need to strip whitespaces before testing for such strings.

def check_if_empty(string):
  if not string.strip():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

empty String
empty String

Using not with str.isspace() method

An empty String is considered false in boolean context and str.isspace() method returns true if there are only whitespace characters in the string and there is at least one character. Using str.isspace() method to check for strings having only whitespaces and not keyword to check for empty strings you can create a condition to check for empty strings including those strings which have only whitespaces.

def check_if_empty(string):
  if not string or string.isspace():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)
str3 = "netjs"
check_if_empty(str3)

Output

empty String
empty String

As you can see both str1 and str2 are considered empty strings.

That's all for this topic Check String Empty or Not in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String join() Method
  2. Getting Substring in Python String
  3. Python continue Statement With Examples
  4. Class And Object in Python
  5. Name Mangling in Python

You may also like-

  1. Interface in Python
  2. Magic Methods in Python With Examples
  3. List Comprehension in Python With Examples
  4. Binary Tree Implementation in Java - Insertion, Traversal And Search
  5. Java Collections Interview Questions And Answers
  6. Difference Between equals() Method And equality Operator == in Java
  7. Using component-scan in Spring to Automatically Discover Bean
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Tuesday, February 18, 2020

Python String join() Method

If you want to join a sequence of Strings in Python that can be done using join() method. Python join() method returns a string which is created by concatenating all the elements in an iterable.

join() method syntax

str.join(iterable)

Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.

str represents a separator that is used between the elements of iterable while joining them.

All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.

Python join() method examples

1. join method with a tuple.

cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)

Output

Chicago:Los Angeles:Seattle:Austin

2. Python join() method with a list of strings.

cities = ['Chicago','Los Angeles','Seattle','Austin']
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

Chicago|Los Angeles|Seattle|Austin

3. TypeError if non-string instance is found.

cities = ['Chicago','Los Angeles','Seattle','Austin', 3]
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

    city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found

In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.

4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.

cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

Austin-Los Angeles-Chicago-Seattle

5. join() method with a Dictionary. In case of dictionary keys are joined not the values.

cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

1-2-3-4

That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce

Sunday, February 16, 2020

Python String split() Method

If you want to split a String in Python that can be done using split() method. Python split() method returns a list of the words in the string, using specified separator as the delimiter, whitespaces are used a separator by default.

split() method syntax

str.split(separator, maxsplit)

Both of the parameters are optional.

separator is the delimiter for splitting a String. If separator is not specified then whitespace is used as separator by default.

maxsplit- Parameter maxsplit specifies the maximum number of splits that are done. If maxsplit is not specified or -1, then there is no limit on the number of splits.

There is also rsplit() method in Python which is similar to split() except for the maxsplit. In case maxsplit is specified in rsplit() method maxsplit splits are done from the rightmost side.

Python split() method examples

1. Using the split method with default parameters (not passing any parameter explicitly).

s = "This is a    test   String"
#break String on spaces
list = s.split()
print(list)

Output

['This', 'is', 'a', 'test', 'String']

Since no parameter is passed with split() method so whitespace is used as separator. Note that runs of consecutive whitespace are regarded as a single separator when default is used.

2. Split string on comma (,) or pipe symbol (|).

s = "Chicago,Los Angeles,Seattle,Austin"
#break String on ,
list = s.split(',')
print(list)

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|')
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle', 'Austin']
['Chicago', 'Los Angeles', 'Seattle', 'Austin']

3. Split string on backslash (\) symbol. With backslash it is better to use escape sequence (\\).

s = "c:\\users\\netjs\\python"
#break String on ,
list = s.split('\\')
print(list)

Output

['c:', 'users', 'netjs', 'python']

4. Limiting the splits using maxsplit parameter. Here split is done for max 2 items.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|', 2)
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle|Austin']

5. Using rsplit() method.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.rsplit('|', 2)
print(list)

Output

['Chicago|Los Angeles', 'Seattle', 'Austin']

That's all for this topic Python String split() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Changing String Case in Python
  2. Python count() method - Counting Substrings
  3. Python Program to Reverse a String
  4. Operator Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. self in Python
  3. Namespace And Variable Scope in Python
  4. raise Statement in Python Exception Handling
  5. PermGen Space Removal in Java 8
  6. String join() Method And StringJoiner Class in Java
  7. Spring Web MVC Java Configuration Example
  8. Data Compression in Hadoop

Saturday, February 15, 2020

Changing String Case in Python

In this tutorial we’ll go through all the methods which are used for changing string case in Python.

In Python there are various methods for changing case of String and also for checking if String is lower case, upper case etc.

Summary of the methods for changing String case in Python

  1. str.lower()- Return a copy of the string with all the cased characters converted to lowercase.
  2. str.upper()- Return a copy of the string with all the cased characters converted to uppercase.
  3. str.capitalize()- Return a copy of the string with its first character capitalized and the rest lowercased.
  4. str.title()- Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

There there are also methods to check the String case, these methods can be used to verify if changing case is really required or not.

  1. str.islower()- Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
  2. str.isupper()- Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
  3. str.istitle()- Return true if the string is a titlecased string and there is at least one character.

Changing String case in Python examples

1. Changing String to all lower case or to all upper case.

s = "This is a TEST String"
print('String in all lower case-',s.lower())
s = "This is a Test String"
print('String in all upper case-', s.upper())

Output

String in all lower case- this is a test string
String in all upper case- THIS IS A TEST STRING

2. Capitalizing the String. First character will be capitalized, if there is any other upper case character in the String that is lower cased.

s = "this is a TEST String"
print('String Capitalized-',s.capitalize())

Output

String Capitalized- This is a test string

3. String title cased. Using title() method you can title cased a String. This method capitalizes the first character of every word.

s = "this is a TEST String"
print('String Title cased-',s.title())

Output

String Title cased- This Is A Test String

4. Checking the case before changing. You can also check the case before changing the case of the String and change the case only if needed. This is an optimization because any String modification method results in a creation of a new String as String is immutable in Python.

s = "this is a test string"
#change only if not already in lower case
if not s.islower():
    s = s.lower()
else:
    print('String already in lower case')
print(s)

Output

String already in lower case
this is a test string
s = "This is a test String"
#change only if not already in upper case
if not s.isupper():
    s = s.upper()
else:
    print('String already in upper case')
print(s)

Output

THIS IS A TEST STRING

That's all for this topic Changing String Case in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Getting Substring in Python String
  2. String Slicing in Python
  3. String Length in Python - len() Function
  4. Convert String to float in Python
  5. Python Program to Check Armstrong Number

You may also like-

  1. Python continue Statement With Examples
  2. Encapsulation in Python
  3. Class And Object in Python
  4. List in Python With Examples
  5. Just In Time Compiler (JIT) in Java
  6. Bucket Sort Program in Java
  7. Spring MVC Exception Handling Tutorial
  8. What is Hadoop Distributed File System (HDFS)

Friday, February 14, 2020

Getting Substring in Python String

In this post we’ll see how to get a substring from a string in Python. Driven by habit most of the developers look for a method in the str class for getting a substring but in Python there is no such method. Getting a substring from a string is done through String slicing in Python.

Format of String slicing is as follows-

Stringname[start_position: end_position: increment_step]

start_position is the index from which the string slicing starts, start_position is included.

end_position is the index at which the string slicing ends, end_position is excluded.

increment_step indicates the step size. For example if step is given as 2 then every alternate character from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at string_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

Getting substring through Python string slicing examples

1. A simple example where substring from index 2..3 is required.

s = "Test String"
print(s[2: 4: 1])
st

Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.

2. Access only the month part from a date in dd/mm/yyyy format. In this case you can use find method to specify the start and end positions for getting a substring.

s = "18/07/2019"
month = s[s.find("/")+1: s.rfind("/") : 1]
print('Month part of the date is-', month)
Month part of the date is- 07

That's all for this topic Getting Substring in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Accessing Characters in Python String
  2. Python count() method - Counting Substrings
  3. Comparing Two Strings in Python
  4. Convert String to int in Python
  5. Functions in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. self in Python
  3. Polymorphism in Python
  4. Python while Loop With Examples
  5. Zipping Files And Folders in Java
  6. Java Collections Interview Questions And Answers
  7. Spring Object XML Mapping (OXM) JAXB Example
  8. How to Create Ubuntu Bootable USB

Thursday, February 13, 2020

Python count() method - Counting Substrings

If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that.

Format of the count() method in Python is as follows-

str.count(sub, start, end)

Here sub is the substring which has to be counted in the String str. Parameters start and end are optional, if provided occurrences of substring would be counted with in that range otherwise whole string length is taken as range.

Python string count() method example

1. Using count() method with no start and end parameters.

s = "This a test string to test count method"
print('Count-', s.count("test"))

Output

Count- 2

2. Using count() method with start and end parameters.

s = "This a test string to test count method"
# passing range for search 
count = s.count("test", s.find("test"), s.rfind("test"))
print('Count-', count)

Output

Count- 1

In the example range for search is passed using find() and rfind() methods, where find() returns the lowest index in the string where substring is found and rfind() returns the highest index in the string where substring sub is found.

3. Calculating count of character ‘o’ in the String.

s = "This a test string to test count method"
count = s.count("o")
print('Count-', count)

Output

Count- 3

That's all for this topic Python count() method - Counting Substrings. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Count Number of Words in a String
  4. Passing Object of The Class as Parameter in Python
  5. raise Statement in Python Exception Handling

You may also like-

  1. Python return Statement With Examples
  2. Global Keyword in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Program to Display Prime Numbers
  5. final Keyword in Java With Examples
  6. Binary Tree Traversal Using Depth First Search Java Program
  7. Spring Profiles With Examples
  8. Input Splits in Hadoop

Wednesday, February 12, 2020

Accessing Characters in Python String

Python String is an ordered sequence of characters and stored as an array. In order to access characters in a String you need to specify string name followed by index in the square brackets. Note that index is 0 based and valid range for string of length n is 0..(n-1).

In String in Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

Accessing characters from String in Python

Getting characters from a string in Python example

s = "Hello World"
#first character
print(s[0])
#3rd character
print(s[2])
print('length of String', len(s))
#last character
print(s[len(s)-1])

Output

H
l
length of String 11
d

Getting characters using negative indexing

s = "Hello World"
# last character
print(s[-1])
print('length of String', len(s))
# first character by making the index negative
print(s[-(len(s))])

Output

d
length of String 11
H

That's all for this topic Accessing Characters in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. String Length in Python - len() Function
  4. Python while Loop With Examples
  5. Multiple Inheritance in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Python Program to Find Factorial of a Number
  3. Python Functions : Returning Multiple Values
  4. Tuple in Python With Examples
  5. BigDecimal in Java
  6. Java ThreadLocal Class With Examples
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Tuesday, February 11, 2020

Removing Spaces From String in Python

If you have to remove spaces from a string in Python you can use one of the following options based on whether you want to remove leading spaces, trailing spaces, spaces from both ends or spaces in between the words too.

  • str.lstrip()- Using this method you can remove the leading whitespaces from a String. See example.
  • str.rstrip()- using this Python String method you can remove the trailing whitespaces from a String. See example.
  • str.strip()- This method helps in removing both leading and trailing whitespaces from a String in Python. See example.
  • re.sub()- By using re (Regular Expression) module's re.sub() function and passing the regular expression for spaces and replacement as a single space you can remove spaces in between words too apart from both leading and trailing whitespaces. See example.

Note that String is immutable in Python so these methods return a new copy of the String which has to be assigned to a String to store the new reference, otherwise the modified string is lost.

lstrip() - Removing leading whitepaces from String in Python

To remove spaces from the start of the String lstrip() method can be used.

string = "    String with leading spaces"
print(string)
print(string.lstrip())

Output

    String with leading spaces
String with leading spaces

rstrip() - Removing trailing whitepaces from String in Python

To remove spaces from the end of the String rstrip() method can be used.

string = "String with trailing spaces    "
print(string)
print(string.rstrip())

Output

String with trailing spaces     
String with trailing spaces

strip() - Removing both leading and trailing whitespaces from String in Python

To remove spaces from both start and end of the String strip() method can be used.

string = "       String with leading and trailing spaces    "
print(string)
print(string.strip())

Output

       String with leading and trailing spaces    
String with leading and trailing spaces

Using re.sub() function in Python

You need to import re module to use this function. Function re.sub() replaces one or many matches with a replacement string.

In the function “//s+” is passed as a regular expression to match any number of spaces. As a replacement for those matches you can pass “” when removing leading and trailing spaces and a single space (“ ”) when removing spaces in between words.

^- represents start of the String

$- represents end of the String

string = "       String with    leading and    trailing spaces    "
print(string)
# removing leading and trailing spaces
string = re.sub("^\\s+|\\s+$", "", string)
# replacing more than one space between words with single space
string = re.sub("\\s+", " ", string)
print(string)

Output

       String with    leading and    trailing spaces    
String with leading and trailing spaces

That's all for this topic Removing Spaces From String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Comparing Two Strings in Python
  2. String Slicing in Python
  3. Getting Substring in Python String
  4. Operator Overloading in Python
  5. Polymorphism in Python

You may also like-

  1. Class And Object in Python
  2. pass Statement in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Python Exception Handling - try,except,finally
  5. Conditional Operators in Java
  6. HashSet in Java With Examples
  7. Race Condition in Java Multi-Threading
  8. Different Bean Scopes in Spring

Sunday, February 9, 2020

Check if String Present in Another String in Python

In Python if you want to check if a given String is present in another String then you have following options-

  • Use Python membership operators ‘in’ and ‘not in’. See example.
  • Using find() method to check if string contains another string. See example.
  • Using index() method to get the index of the substring with in the String. See example.

Python membership operators - in and not in

If you want to check if a String is member of another String then you can use ‘in’ and ‘not in’ membership operators.

  • ‘in’ operator- Returns true if the string is part of another string otherwise false.
  • ‘not in’ operator- Returns true if the string is not part of another string otherwise false.

Python in operator example

def check_membesrship(str1, str2):
  if str2 in str1:
    print(str2, 'found in String')
  else:
    print(str2, 'not found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String
That not found in String

Python not in operator example

def check_membesrship(str1, str2):
  if str2 not in str1:
    print(str2, 'not found in String')
  else:
    print(str2, 'found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, 'That')
#another call
check_membesrship(str1, str2)

Output

That not found in String
Python found in String

Using find() method to check if substring exists in string

Using find() method in Python you can check if substring is part of the string or not. If found, this method returns the location of the first occurrence of the substring otherwise -1 is returned.

Python find() method example

def check_membesrship(str, substr):
  loc = str.find(substr)
  if loc == -1:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

Using index() method to check if substring exists in string

Using index() method in Python you can check if substring is part of the string or not. This method is similar to find() and returns the location of the first occurrence of the substring if found. If not found then index() method raises ‘ValueError’ exception that's where it differs from find().

Python index() method example

def check_membesrship(str, substr):
  # Catch ValueError exception
  try:
    loc = str.index(substr)
  except ValueError:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

That's all for this topic Check if String Present in Another String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Accessing Characters in Python String
  3. Python String join() Method
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. Difference Between Function and Method in Python
  5. instanceof Operator in Java
  6. Java Exception Handling Tutorial
  7. Checking Number Prime or Not Java Program
  8. Spring Setter Based Dependency Injection

Saturday, February 8, 2020

String Length in Python - len() Function

To find length of String in Python you can use len() function.

Syntax of len() function

len(str)

Where str is the String parameter. This function returns the length of the passed String as an integer, which represents the number of characters in the String.

String length using len() in Python

str = "netjs"
print(len(str))

str = "Hello World!"
strLen = len(str)
print('length of String- ',strLen)

Output

5
length of String-  12

That's all for this topic String Length in Python - len() Function. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Python String split() Method
  3. Python Program to Check if Strings Anagram or Not
  4. Class And Object in Python
  5. Inheritance in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Namespace And Variable Scope in Python
  3. List in Python With Examples
  4. Tuple in Python With Examples
  5. Access Modifiers in Java
  6. How to Convert Date And Time Between Different Time-Zones in Java
  7. Spring Component Scan Example
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Friday, February 7, 2020

String Slicing in Python

String in Python is stored as an array so array indexing can be used to access characters of a String, for example str[0] returns first character of the String str. You may have a scenario where you want to access a part of String rather than a single character, in that case you can use string slicing using slice operator in Python.

Python string slicing

Format of String slicing is as follows-

Stringname[start_position: end_position: increment_step]
  • start_position is the index from which the string slicing starts, start_position is included.
  • end_position is the index at which the string slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate character from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at string_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

Python string slicing examples

1- A simple example where substring from index 2..3 is required.

s = "Python String Slicing"
print(s[2: 4: 1])

Output

th

Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.

2- If no parameters are specified.

s = "Python String Slicing"
#both are valid
print(s[:])
print(s[: :])

Output

Python String Slicing
Python String Slicing

3- String slicing when step size is greater than one.

s = "Python String Slicing"
print(s[3: 8 : 2])

Output

hnS

Since the step size is 2 so every other character with in the limits of start_pos and end_pos is accessed.

4- Using string slicing in conjunction with other Python string methods. For example if there is a data in dd/mm/yyyy format and you want to access only the month part. In this case you can use index method to specify the start and end positions for slicing.

s = "03/05/2019"
print(s[s.index("/")+1: s.rindex("/") : 1])

Output

05

String slicing with negative indexing

In string in Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

Python string slice

1- Reversing the string using slicing. By providing increment_step as -1 you can reverse a string.

s = "Hello World"
reversed = s[: :-1]
print(reversed)

Output

dlroW olleH

2- Using negative value as start position and step size is +1.

s = "Hello World"
str = s[-5: :]
print(str)

Output

World

Here step size is +1 so the indices that are accessed are -5, -4, -3, -2, -1

That's all for this topic String Slicing in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Comparing Two Strings in Python
  2. Python String isdigit() Method
  3. Python Program to Check Whether String is Palindrome or Not
  4. Encapsulation in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. pass Statement in Python
  2. Global Keyword in Python With Examples
  3. self in Python
  4. Constructor in Python - __init__() function
  5. How HashMap Internally Works in Java
  6. Creating PDF in Java Using Apache PDFBox
  7. HDFS Federation in Hadoop Framework
  8. Spring MVC Form Example With Bean Validation

Thursday, February 6, 2020

Strings in Python With Method Examples

String which represents a sequence of characters is one of the most used type in most of the applications. So programming languages generally ensure that String is well optimized and has an extensive API with methods to cover most of the String operations. Python is no different and String in Python has also many optimization features and lots of methods.

Python String

String in Python is of type “str” which means every String literal created is an object of str class. strings in Python are arrays of bytes representing unicode characters.

For characters there is no separate data type in Python, a single character is also string of length 1.


Creating a String in Python

You can create a String in Python by enclosing a group of characters in either single quotes or double quotes.

Both of the following are valid and work in similar way-

s = 'Hello'

s = "Hello"

You can also create String in Python using tripe single quotes or triple double quotes. This way of creating String is useful if you have a multiline String.

s = '''This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.'''

print(s)

Output

This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.

Showing quotes as part of String in Python

If you have to show quotes as part of string then you can use another type of quote to enclose string and the quote which has to be part of string in the inner string.

For example if you have to show text – This isn’t part of the original deal
then use double quotes to enclose the String and single quote as part of the text.

s = "This isn't part of the deal"
print(s)

Output

This isn't part of the deal

If you have to show text- He said “May I come in”
then use single quotes to enclose the String and double quotes as part of the text.

s = 'He said "May I come in"'
print(s)

Output

He said "May I come in"

Escape characters in a String

You can also use escape characters with a String in Python.

Some of the escape characters that can be used in Strings are-

Escape character Description
\aBell or alert
\bBackspace
\nNew line
\rCarriage return (enter)
\sSpace
\tHorizontal tab space
\vVertical tab space

For example-

s = "This text has \t spaces and goes to \n next line"
print(s)

Output

This text has   spaces and goes to 
 next line

Backslash (\) is also used as an escape sequence in Python. If you want double or single quote with in a String then you can also put a backslash followed by a quote (\" or \').

s = "He said \"this looks good\" to his colleague"
print(s)

Output

He said "this looks good" to his colleague

Since backslash is used as an escape sequence so you’d need two backslashes (\\) if you have to display backslash as part of String. One for displaying and another as escape sequence.

print("C:\\Python\\")
print(s)

Output

C:\Python\

Accessing characters in String (String indexing)

Since String in Python is stored as an array so array indexing can be used to access characters of a String. Index is 0 based so first character is at index 0, second is at index 1 and so on.

In Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

String in Python

Example to access characters of a String

s = "Hello World"
#first character
print(s[0])
#last character
print(s[10])
#last character
print(s[-1])
#first character
print(s[-11])

Output

H
d
d
H

Trying to use an index which is out of range results in IndexError. Using any other type except integer as index results in TypeError.

s = "Hello World"
#index out of range
print(s[12])

Output

    print(s[12])
IndexError: string index out of range

If you want to access a part of a String then you use slicing operator. Slicing is done using “[:]” operator.

For example if you want to access characters between index 3 and 7.

s = "Hello World"
#slicing String
print(s[3:7])

Output

lo W

For more examples of Python String slicing please refer this post- String Slicing in Python

Strings in Python are immutable

String in Python is immutable which means content of String object can’t be modified once assigned.

Trying to modify a String by updating or deleting any character results in error as Strings are immutable.

Updating String

s = "Hello World"
#changing String
s[3] = 't'

Output

    s[3] = 't'
TypeError: 'str' object does not support item assignment

Deleting character in a String

s = "Hello World"
#deleting char
del s[3]

Output

    del s[3]
TypeError: 'str' object doesn't support item deletion

Note that for immutable object though content can’t be changed but the reference can be changed. So a string object can be made to reference a new String.

s = "Hello World"
print(id(s))
s = "Hi"
print(s)
print(id(s))

Output

2976589114032
Hi
2976587746472

id function in CPython implementation returns the address of the object in memory. As you can see s starts referencing to the new memory location when a new String is assigned.

String interning in Python

String interning means that two string objects that have the same value share the same memory. If you have one string object with some value and you create second string object with the same value then the second string object shares the reference with the first string object. By interning strings memory is saved.

String interning is possible in Python as Strings are immutable so content can't be changed.

s1 = "Hello"
s2 = "Hello"
print(s1 is s2)
print(id(s1))
print(id(s2))

Output

True
1347382642256
1347382642256

In the example two string objects are created having the same value. As you can see when is operator is used to check whether both the operands refer to the same object or not true is returned.

Also id() function returns the same memory address for both the objects.

Operators used with String

Following operators are used with String in Python-

1. + operator-‘+’ operator when used with Strings in Python acts as a concatenation operator . It is used to append one string at the end of another string.

s1 = "Hello"
s2 = " World"
print(s1 + s2)

Output

Hello World

2. * operator- * operator is the repetition operator and used to repeat the string for the given number of times.

s1 = '*'
for i in range (1, 5):
    print(s1*i)

Output

*
**
***
****

3. in and not in operators- These operators are used for checking whether the given string or character is part of another String.

4. Slice operator- Slice operator ([:]) is used to access a substring with in a string. See more about Python string slicing here.

Python String methods

In this section Python String methods are compiled functionality wise.

  1. Getting String length in Python- For getting string length in Python, len() function is used. Refer String Length in Python - len() Function to see examples of len() function with strings.
  2. Checking String membership- To check if String present in another string in Python you can use membership operators ‘in’ and ‘not in’ or use find() or index() methods. Refer Check if String Present in Another String in Python to see examples of String membership checking.
  3. Comparing two Strings in Python- For comparing two Strings in Python you can use relational operators (==, <, <=, >, >=, !=). Refer Comparing Two Strings in Python to see examples of String comparison.
  4. Removing spaces from String in Python- To rempve spaces in String you can use str.lstrip(), str.rstrip() and str.strip() methods. Refer Removing Spaces From String in Python to see examples of removing spaces from string.
  5. Python count() method- If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that. Refer Python count() method - Counting Substrings to see examples of count() method.
  6. Changing String case in Python- If you want to change string to lower case or upper case you can use one of the methods provided in str- str.lower(), str.upper(), str.capitalize(), str.title() to do that. Refer Changing String Case in Python to see examples of string case changing.
  7. split() Method- If you want to split a String in Python that can be done using split() method. Refer Python String split() Method to see examples of splitting a String using split() method.
  8. join() Method- If you want to join a sequence of Strings in Python that can be done using join() method. Refer Python String join() Method to see examples of join() method.
  9. str.isspace() Method- This method returns true if there are only whitespace characters in the string and there is at least one character. Refer Check String Empty or Not in Python to see example of isspace() method.
  10. isdigit() Method-The isdigit() method in Python String class is used to check if all the characters in the string are digits or not. Refer Python String isdigit() Method to see example of isdigit() method.
  11. isnumeric() Method-The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not. Refer Python String isnumeric() Method to see example of isnumeric() method.

That's all for this topic Strings in Python With Method Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Accessing Characters in Python String
  2. Getting Substring in Python String
  3. Python Program to Count Number of Words in a String
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. instanceof Operator in Java
  5. Difference Between ArrayList And LinkedList in Java
  6. Semaphore in Java Concurrency
  7. Spring Setter Based Dependency Injection
  8. Transaction Management in Spring

Wednesday, February 5, 2020

User-defined Exceptions in Python

In this Python Exception Handling Tutorial series we'll see how to write user defined exceptions in Python.

Though Python has many built-in exception covering a lot of error scenarios but sometimes you as a user would want to create your own exception for a specific scenario in order to make error messages more relevant to the context. Such exceptions are called user-defined exceptions or custom exceptions.

User-defined exception in Python

To create a custom exception in Python you need to create a new exception class. That custom exception class should typically be derived from the Exception class (built in Exception class), either directly or indirectly.

Since your exception class is a class it can theoretically be defined to do anything any other class can do, but usually user-defined exception classes are kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

As a convention your custom exception should be defined with name that end in “Error”, similar to the naming of the standard exceptions.

User-defined exception Python example

Suppose you have a Python function that take age as a parameter and tells whether a person is eligible to vote or not. Voting age is 18 or more.

If person is not eligible to vote you want to raise an exception using raise statement, for this scenario you want to write a custom exception named “InvalidAgeError”.

# Custom exception
class InvalidAgeError(Exception):
  def __init__(self, arg):
    self.msg = arg

def vote_eligibility(age):
  if age < 18:
    raise InvalidAgeError("Person not eligible to vote, age is " + str(age))
  else:
    print('Person can vote, age is', age)

# calling function
try:
  vote_eligibility(22)
  vote_eligibility(14)
except InvalidAgeError as error:
  print(error)

Output

Person can vote, age is 22
Person not eligible to vote, age is 14

Hierarchical custom exceptions

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:

class Error(Exception):
  """Base class for exceptions in this module."""
  pass

class InputError(Error):
  """Exception raised for errors in the input.

  Attributes:
    expression -- input expression in which the error occurred
    message -- explanation of the error
  """

  def __init__(self, expression, message):
    self.expression = expression
    self.message = message

That's all for this topic User-defined Exceptions in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Exception Handling - try,except,finally
  2. Python assert Statement
  3. Passing Object of The Class as Parameter in Python
  4. Name Mangling in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Getting Substring in Python String
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Python Program to Display Prime Numbers
  5. HashSet in Java With Examples
  6. Java Multithreading Interview Questions And Answers
  7. Switch-Case Statement in Java
  8. Spring Email Scheduling Example Using Quartz Scheduler

Tuesday, February 4, 2020

raise Statement in Python Exception Handling

In Python Exception Handling - try,except,finally we saw some examples of exception handling in Python but exceptions, in all the examples there, were thrown automatically. You can throw an exception manually too using raise statement in Python.

Python raise statement

For throwing an exception using raise there are the following options-

1. You can simply use raise without any other expression. If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a RuntimeError exception is raised indicating that this is an error.

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    #raise with no expression
    raise

divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

As you can see raise statement re-raises the last exception again.

2. If raise is used with an expression then raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    raise RuntimeError("An error occurred")

divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 9, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 6, in divide_num
    raise RuntimeError("An error occurred")
RuntimeError: An error occurred

As you can see in this case previous exception is attached as the new exception’s __context__ attribute.

3. raise can also be used with from clause for exception chaining. With the from clause another exception class or instance is given, which will then be attached to the raised exception as the __cause__ attribute.

In the example there are two functions, from function func() there is a call to function divide_num with arguments that cause ZeroDivisionError.

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    raise RuntimeError("An error occurred") from error

def func():
  try:
    divide_num(10, 0)
  except RuntimeError as obj:
    print(obj)
    print(obj.__cause__)

func()

Output

Zero is not a valid argument here
An error occurred
division by zero

As you can see using __cause__ attribute you can get the attached exception.

That's all for this topic raise Statement in Python Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Interface in Python
  5. Python break Statement With Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Default Arguments in Python
  4. Python Program to Display Armstrong Numbers
  5. HashMap in Java With Examples
  6. this Keyword in Java With Examples
  7. Introduction to Hadoop Framework
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Monday, February 3, 2020

Python Exception Handling - try,except,finally

In this article we’ll see how to handle exceptions in Python using try, except and finally statements.

Python exception handling

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

General form of exception handling in Python using try, except finally is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

Some important points to note here are-

  1. If no exception is raised then the statements in the else block are executed.
  2. Else and finally blocks are not mandatory.
  3. You can have multiple except blocks to handle multiple exceptions.
  4. try block must be followed either by except or finally.
  5. If finally block is there it is always executed whether an exception is raised or not.

Using try, except for exception handling

Let’s try to understand how exception handling in Python using try and except helps in writing robust code. Here is an example where a list is passed to a function and every element in the list is used to divide a number. Just notice what happens if one of the number in the list is zero.

def divide_num(num_list):
  for num in num_list:
    print(10/num)

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
Traceback (most recent call last):

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide_num(num_list)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 3, in divide_num
    print(10/num)
ZeroDivisionError: division by zero

As you can see dividing by zero raises ZeroDivisionError, since code doesn’t provide any exception handling code of its own so default exception handling is used. Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

As you can see program is terminated and only the exception message is displayed by the default exception handling which is not that user friendly.

Python exception handling with try, except

Now let’s write that same code by providing exception handling with in the code using try and except.

def divide_num(num_list):
  for num in num_list:
    try:
      print(10/num)
    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    else:
      print('in else block')

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
in else block
1.6666666666666667
in else block
division by zero
Zero is not a valid argument here
1.4285714285714286
in else block

As you can see now the code that may throw an exception is enclosed with in a try block. When the exception is raised in the try block exception handler looks for the except block that can handle the exception of that type. In the code ZeroDivisionError is raised and there is an except block that handles ZeroDivisionError so that except block handles the raised exception. Program is not terminated now when the exception is raised because of the exception handling in the code.

except block in Python

There are various ways to write except block while writing exception handling code in Python.

  1. You can catch the exception as an object that gives description about the raised exception.
     except ZeroDivisionError as error:
     
  2. You can write except block with the exception class name only.
     except Exception_Class_Name:
     
  3. You can handle multiple exceptions by using multiple except blocks or you can use a single except block and write multiple exceptions as a tuple.

    For example multiple except blocks-

    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    except TypeError:
      print('Argument is not of valid type') 
      

    Single except block with multiple exceptions

      except (ZeroDivisionError, TypeError):
      
  4. You can write except with out specifying exception class. That way except block catches any type of exception. Though that is not considered good practice as it is too broad exception clause and you won’t be able to determine specifically which exception has been raised.
      except:
        print('An exception has occurred')
      

Multiple except block Python example

def divide_num(num_list):
  for num in num_list:
    try:
      print(10/num)
    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    except TypeError as error:
      print(error)
      print('Argument is not of valid type-', num)

num_list = [5, 6, 'a', 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
unsupported operand type(s) for /: 'int' and 'str'
Argument is not of valid type- a
1.4285714285714286

finally in Python exception handling

If finally is present, it specifies a ‘cleanup’ handler. The finally clause is always executed whether an exception is raised in the try block or not. That ensures that all the resources are properly cleaned up.

def divide_num(num):
  try:
    f = open("testfile", "a")
    r = 10/num
    f.write("Result 10/%d is %d" %(num,r))
  except ZeroDivisionError as error:
    print(error)
    print('Zero is not a valid argument here')
  except FileNotFoundError as error:
    print(error)
    print('Passed file does not exist')

  finally:
    print('closing file')
    f.close()

divide_num(0)

Output

division by zero
Zero is not a valid argument here
closing file

If function is called with a valid argument and no exception is raised even then finally block is executed. For example calling function as given here.

divide_num(2)

Output

closing file

If there is a return, break or continue statement in try block even then finally clause is executed.

def divide_num():
  try:
    return 'try'
  finally:
    print('In finally clause')

a = divide_num()
print(a)

Output

In finally clause
try

If there is a return statement in finally too then that becomes the last return statement to be executed. Since the return value of a function is determined by the last return statement executed so value returned by finally clause is the value returned by the function.

def divide_num():
  try:
    return 'try'
  finally:
    print('In finally clause')
    return 'finally'

a = divide_num()
print(a)

Output

In finally clause
finally

That's all for this topic Python Exception Handling - try,except,finally. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. raise Statement in Python Exception Handling
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Abstract Class in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Keyword Arguments in Python
  4. Python Program to Display Fibonacci Series
  5. Java Collections Interview Questions And Answers
  6. this Keyword in Java With Examples
  7. What is Hadoop Distributed File System (HDFS)
  8. Spring Object XML Mapping (OXM) JAXB Example