Trending February 2024 # Polymorphism In Python With Examples # Suggested March 2024 # Top 6 Popular

You are reading the article Polymorphism In Python With Examples updated in February 2024 on the website Cancandonuts.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Polymorphism In Python With Examples

What is Polymorphism?

Polymorphism can be defined as a condition that occurs in many different forms. It is a concept in Python programming wherein an object defined in Python can be used in different ways. It allows the programmer to define multiple methods in a derived class, and it has the same name as present in the parent class. Such scenarios support method overloading in Python.

In this Python Polymorphism tutorial, you will learn:

Polymorphism in Operators

An operator in Python helps perform mathematical and several other programming tasks. For example, the ‘+’ operator helps in performing addition between two integer types in Python, and in the same way, the same operator helps in concatenating strings in Python programming.

Let us take an example of + (plus) operator in Python to display an application of Polymorphism in Python as shown below:

Python Code:

p = 55 q = 77 r = 9.5 g1 = "Guru" g2 = "99!" print("the sum of two numbers",p + q) print("the data type of result is",type(p + q)) print("The sum of two numbers",q + r) print("the data type of result is", type (q + r)) print("The concatenated string is", g1 + g2) print("The data type of two strings",type(g1 + g2))

Output:

the sum of two numbers 132 The sum of the two numbers 86.5 The concatenated string is Guru99!

The above example can also be regarded as the example of operator overloading.

Polymorphism in user-defined methods

A user-defined method in the Python programming language are methods that the user creates, and it is declared using the keyword def with the function name.

Polymorphism in the Python programming language is achieved through method overloading and overriding. Python defines methods with def keyword and with the same name in both child and parent class.

Let us take the following example as shown below: –

Python Code:

from math import pi class square: def __init__(self, length): self.l = length def perimeter(self): return 4 * (self.l) def area(self): return self.l * self.l class Circle: def __init__(self, radius): self.r = radius def perimeter(self): return 2 * pi * self.r def area(self): return pi * self.r * * 2 # Initialize the classes sqr = square(10) c1 = Circle(4) print("Perimeter computed for square: ", sqr.perimeter()) print("Area computed for square: ", sqr.area()) print("Perimeter computed for Circle: ", c1.perimeter()) print("Area computed for Circle: ", c1.area())

Output:

Perimeter computed for square:  40 Area computed for square:  100 Perimeter computed for Circle:  25.132741228718345 Area computed for Circle:  50.26548245743669

In the above code, there are two user-defined methods, perimeter and area, defined in circle and square classes.

As shown above, both circle class and square class invoke the same method name displaying the characteristic of Polymorphism to deliver the required output.

Polymorphism in Functions

The built-in functions in Python are designed and made compatible to execute several data types. In Python, Len() is one of the key built-in functions.

It works on several data types: list, tuple, string, and dictionary. The Len () function returns definite information aligned with these many data types.

The following figure shows how Polymorphism can be applied in Python with relation to in-built functions: –

Following program helps in illustrating the application of Polymorphism in Python: –

Python Code:

print ("The length of string Guru99 is ",len("Guru99")) print("The length of list is ",len(["Guru99","Example","Reader"])) print("The length of dictionary is ",len({"Website name":"Guru99","Type":"Education"}))

Output:

The length of string Guru99 is 6 The length of the list is 3 The length of the dictionary is 2

In the above example, Len () function of Python performs Polymorphism for string, list, and dictionary data types, respectively.

Polymorphism and Inheritance

Inheritance in Python can be defined as the programming concept wherein a child class defined inherit properties from another base class present in Python.

There are two key Python concepts termed method overriding and method overloading.

In method overloading, Python provides the feature of creating methods that have the same name to perform or execute different functionalities in a given piece of code. It allows to overload methods and uses them to perform different tasks in simpler terms.

In Method overriding, Python overrides the value that shares a similar name in parent and child classes.

Let us take the following example of Polymorphism and inheritance as shown below: –

Python Code:

class baseclass: def __init__(self, name): chúng tôi = name def area1(self): pass def __str__(self): return self.name class rectangle(baseclass): def __init__(self, length, breadth): super().__init__("rectangle") self.length = length self.breadth = breadth def area1(self): return self.length * self.breadth class triangle(baseclass): def __init__(self, height, base): super().__init__("triangle") self.height = height self.base = base def area1(self): return (self.base * self.height) / 2 a = rectangle(90, 80) b = triangle(77, 64) print("The shape is: ", b) print("The area of shape is", b.area1()) print("The shape is:", a) print("The area of shape is", a.area1())

Output:

The shape is: a triangle The area of a shape is 2464.0 The shape is: a rectangle The area of a shape is 7200

In above code, the methods have the same name defined as init method and area1 method. The object of class square and rectangle are then used to invoke the two methods to perform different tasks and provide the output of the area of square and rectangle.

Polymorphism with the Class Methods

The Python programming enables programmers to achieve Polymorphism and method overloading with class methods. The different classes in Python can have methods that are declared in the same name across the Python code.

In Python, two different classes can be defined. One would be child class, and it derives attributes from another defined class termed as parent class.

The following example illustrates the concept of Polymorphism with class methods: –

Python Code:

class amazon: def __init__(self, name, price): chúng tôi = name self.price = price def info(self): print("This is product and am class is invoked. The name is {self.name}. This costs {self.price} rupees.") class flipkart: def __init__(self, name, price): chúng tôi = name self.price = price def info(self): print(f "This is product and fli class is invoked. The name is {self.name}. This costs {self.price} rupees.") FLP = flipkart("Iphone", 2.5) AMZ = amazon("Iphone", 4) for product1 in (FLP, AMZ): product1.info()

Output:

This is a product, and fli class is invoked. The name is iPhone, and this costs 2.5 rupees. This is a product, and am class is invoked. The name is iPhone, and this costs 4 rupees.

In the above code, two different classes named as flipkart and amazon use the same method names info and init to provide respective price quotations of the product and further illustrate the concept of Polymorphism in Python.

Difference between Method overloading and compile-time Polymorphism

In compile-time Polymorphism, the compiler of the Python program resolves the call. Compile-time Polymorphism is accomplished through method overloading.

The Python compiler does not resolve the calls during run time for polymorphism. It is also classified as method overriding wherein the same methods carry similar signatures or properties, but they form a part of different classes.

Summary:

Polymorphism can be defined as a condition that occurs in many different forms.

An operator in Python helps perform mathematical and several other programming tasks.

A user-defined method in the Python programming language are methods that the user creates, and it is declared using the keyword def with the function name.

Polymorphism in Python offers several desirable qualities, such as it promotes the reusability of codes written for different classes and methods.

A child class is a derived class, and it gets its attributes from the parent class.

The Polymorphism is also achieved through run-time method overriding and compile-time method overloading.

Polymorphism in Python is also attained through operator overloading and class methods.

You're reading Polymorphism In Python With Examples

Steps To Avoid Eoferror In Python With Examples

Introduction to Python EOFError

EOFError in python is one of the exceptions handling errors, and it is raised in scenarios such as interruption of the input() function in both python version 2.7 and python version 3.6 and other versions after version 3.6 or when the input() function reaches the unexpected end of the file in python version 2.7, that is the functions do not read any date before the end of input is encountered. And the methods such as the read() method must return a string that is empty when the end of the file is encountered, and this EOFError in python is inherited from the Exception class, which in turn is inherited from BaseException class.

Syntax:

EOFError: EOF when reading a line

Working of EOFError in Python

Below is the working of EOFError:

1. BaseException class is the base class of the Exception class which in turn inherits the EOFError class.

2. EOFError is not an error technically, but it is an exception. When the in-built functions such as the input() function or read() function return a string that is empty without reading any data, then the EOFError exception is raised.

3. This exception is raised when our program is trying to obtain something and do modifications to it, but when it fails to read any data and returns a string that is empty, the EOFError exception is raised.

Examples

Below is the example of Python EOFError:

Example #1

Python program to demonstrate EOFError with an error message in the program.

Code:

#EOFError program #try and except blocks are used to catch the exception try: while True: #input is assigned to a string variable check check = raw_input('The input provided by the user is being read which is:') #the data assigned to the string variable is read print 'READ:', check #EOFError exception is caught and the appropriate message is displayed except EOFError as x: print x

Output:

Explanation: In the above program, try and except blocks are used to catch the exception. A while block is used within a try block, which is evaluated to true, and as long as the condition is true, the data provided by the user is read, and it is displayed using a print statement, and if the data cannot be read with an empty string being returned, then the except block raises an exception with the message which is shown in the output.

Example #2

Python program to demonstrate EOFError with an error message in the program.

Code:

#EOFError program #try and except blocks are used to catch the exception try: while True: #input is assigned to a string variable check check = raw_input('The input provided by the user is being read which is:') #the data assigned to the string variable is read print 'Hello', check #EOFError exception is caught and the appropriate message is displayed except EOFError as x: print x

Output:

Explanation: In the above program, try and except blocks are used to catch the exception. A while block is used within a try block, which is evaluated to true, and as long as the condition is true, the data provided by the user is read and it is displayed using a print statement, and if the data cannot be read with an empty string being returned, then the except block raises an exception with the message which is shown in the output.

Steps to Avoid EOFError in Python

If End of file Error or EOFError happens without reading any data using the input() function, an EOFError exception will be raised. In order to avoid this exception being raised, we can try the following options which are:

Before sending the End of File exception, try to input something like CTRL + Z or CTRL + D or an empty string which the below example can demonstrate:

Code:

#try and except blocks are used to catch the exception try: data = raw_input ("Do you want to continue?: ") except EOFError: print ("Error: No input or End Of File is reached!") data = "" print data

Output:

Explanation: In the above program, try and except blocks are used to avoid the EOFError exception by using an empty string that will not print the End Of File error message and rather print the custom message provided by is which is shown in the program and the same is printed in the output as well. The output of the program is shown in the snapshot above.

If the EOFError exception must be processed, try and catch block can be used.

Conclusion

In this tutorial, we understand the concept of EOFError in Python through definition, the syntax of EOFError in Python, working of EOFError in Python through programming examples and their outputs, and the steps to avoid EOFError in Python.

Recommended Articles

This is a guide to Python EOFError. Here we discuss the Introduction and Working of Python EOFError along with Examples and Code Implementation. You can also go through our other suggested articles to learn more –

Python Counter In Collections With Example

What is Python Counter?

Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class.

The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.

Why use Python Counter?

Here, are major reasons for using Python 3 Counter:

The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.

It allows you to count the items in an iterable list.

Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.

A Counter can also count elements from another counter

In this Python tutorial you will learn:

Introduction to Python Counter

Python Counter takes in input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element.

Syntax:

Counter(list)

Consider you have a following list :

list1 = ['x','y','z','x','x','x','y', 'z']

The list has elements x , y and chúng tôi you use Counter on this list , it will count how many times x , y and z is present. The output if counter is used on list1 should be something like :

Counter({'x': 4, 'y': 2, 'z': 2})

So we have the count of x as 4, y as 2 and z as 2.

To make use of Counter we need to import it first as shown in the below given example:

from collections import Counter

Here is a simple example , that shows the working of Counter module.

from collections import Counter list1 = ['x','y','z','x','x','x','y', 'z'] print(Counter(list1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2}) Counter with String

In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.

In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.

Example:

from collections import Counter my_str = "Welcome to Guru99 Tutorials!" print(Counter(my_str))

Output:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Counter with List

A list is an iterable object that has its elements inside square brackets.

The elements in the list when given to the Counter will be converted to a hashtable objects wherein the elements will become keys and the values will be the count of the elements from the list given.

For example [‘x’,’y’,’z’,’x’,’x’,’x’,’y’,’z’]. Once you give the list the Counter, it will give you the count of each element in the list.

from collections import Counter list1 = ['x','y','z','x','x','x','y','z'] print(Counter(list1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2}) Counter with Dictionary

A dictionary has elements as key/value pair, and they are written inside curly brackets.

Once the dictionary is given to the Counter, it will be converted to a hashtable objects wherein the elements will become keys, and the values will be the count of the elements from the dictionary given.

For example : {‘x’: 4, ‘y’: 2, ‘z’: 2, ‘z’: 2}. The Counter function will try to find the count of each of the key in the given dictionary.

from collections import Counter dict1 = {'x': 4, 'y': 2, 'z': 2, 'z': 2} print(Counter(dict1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2}) Counter with Tuple

Tuple is a collection of objects separated by commas inside round brackets. Counter will give you the count of each of the elements in the tuple given.

Once the tuple is given to the Counter, it will be converted to a hashtable object wherein the elements will become keys and the values will be the count of the elements from the tuple given.

from collections import Counter tuple1 = ('x','y','z','x','x','x','y','z') print(Counter(tuple1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2})

Accessing, Initializing and Updating Counters Initializing Counter

A Counter can be initialized by passing string value, list, dictionary, or tuple as shown below:

from collections import Counter print(Counter("Welcome to Guru99 Tutorials!")) #using string print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

You can also initialize a empty Counter as shown below:

from collections import Counter _count = Counter() Updating Counter

You can add values to the Counter by using update() method.

_count.update('Welcome to Guru99 Tutorials!')

The final code is :

from collections import Counter _count = Counter() _count.update('Welcome to Guru99 Tutorials!') print(_count)

The output is:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1}) Accessing Counter

To get the values from the Counter, you can do as follows:

from collections import Counter _count = Counter() _count.update('Welcome to Guru99 Tutorials!') print('%s : %d' % ('u', _count['u'])) print('n') for char in 'Guru': print('%s : %d' % (char, _count[char]))

Output:

u : 3 G : 1 u : 3 r : 2 u : 3 Deleting an Element from Counter

To delete an element from Counter you can make use of del , as shown in the example below:

Example:

from collections import Counter dict1 = {'x': 4, 'y': 2, 'z': 2} del dict1["x"] print(Counter(dict1))

Output:

Counter({'y': 2, 'z': 2}) Arithmetic operation on Python Counter

Arithmetic operation like addition, subtraction, intersection and union can be done on a Counter as shown in the example below:

Example:

from collections import Counter counter1 = Counter({'x': 4, 'y': 2, 'z': -2}) counter2 = Counter({'x1': -12, 'y': 5, 'z':4 }) #Addition counter3 = counter1 + counter2 # only the values that are positive will be returned. print(counter3) #Subtraction counter4 = counter1 - counter2 # all -ve numbers are chúng tôi example z will be z = -2-4=-6, since it is -ve value it is not shown in the output print(counter4) #Intersection counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2 print(counter5) #Union print(counter6)

Output:

Counter({'y': 7, 'x': 4, 'z': 2}) Counter({'x1': 12, 'x': 4}) Counter({'y': 2}) Counter({'y': 5, 'x': 4, 'z': 4}) Methods Available on Python Counter

There are some important methods available with Counter, here is the list of same:

most_common(value): This method will return you the most common elements from Counter list.

subtract(): This method is used to deduct the elements from another Counter.

update(): This method is used to update the elements from another Counter.

Example : elements() from collections import Counter counter1 = Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0}) for a in _elements: print(a)

Output:

x x x x x y y Example: most_common(value) from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next. print(common_element) common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the chúng tôi last element will be the least common element. print(common_element1)

Output:

[('y', 12), ('x', 5)] [('y', 12), ('x', 5), ('x1', 0), ('z', -2)] Example:subtract() from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) counter2 = Counter({'x': 2, 'y':5}) counter1.subtract(counter2) print(counter1)

Output:

Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2}) Example:update() from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) counter2 = Counter({'x': 2, 'y':5}) counter1.update(counter2) print(counter1)

Output:

Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2}) Reassigning Counts in Python

You can re-assign counts of Counter as shown below:

Consider you have a dictionary as : {‘x’: 5, ‘y’: 12, ‘z’: -2, ‘x1’:0}

You can change the count of the element as shown below:

from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) counter1['y'] = 20 print(counter1)

Output: After executing you will see that y count is changed from 12 to 20

Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2}) Get and set the count of Elements using Counter

To get the count of an element using Counter you can do as follows:

from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) print(counter1['y']) # this will give you the count of element 'y'

Output:

12

To set the count of the element you can do as follows:

from collections import Counter counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0}) print(counter1['y']) counter1['y'] = 20 counter1['y1'] = 10 print(counter1)

Output:

12 Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2}) Summary:

Counter is a container that will hold the count of each of the elements present in the container.

Counter is a sub-class available inside the dictionary class.

Using the Python Counter tool, you can count the key-value pairs in an object, also called a hashtable object.

The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.

It allows you to count the items in an iterable list.

Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.

A Counter can also count elements from another counter.

The important methods available on a Counter are elements() , most_common(value), subtract() and update().

A counter can be used on a string, list, dictionary, and tuple.

Top 3 Examples To Implement Of Python Curl

Introduction to Python Curl

A curl is a request tool that is used to create network requests so that it allows it to transfer the data across the network, which is done using the command line. In this article, we are going to discussing curl in Python. In python, a curl is a tool for transferring data requests to and from a server using PycURL. This tool is used for testing REST APIs, downloading files, etc. this PycURL is an interface to the libcURL library in Python, and hence the PycURL is capable of inheriting all the capabilities of libcURL.

Working of Python Curl

In this article, Python curl is used for REST API for transferring the data to and from a server. In this, we will see PycURL is a python interface used to fetch the objects from a python program identified by a URL.

Curl is a UNIX command which can send GET, POST, PUT and DELETE request to a URL. There is an HTTP library called “Requests” in Python, but this library needs to be pulled as it’s not any standard module. When this library is used, we can create a simple request, and this request returns a response object which allows access to the various status codes or headers, etc. Let us see an example below with output for each line:

Examples to Implement Python Curl

Below are the examples of Python Curl:

Example #1

Code:

import requests print url

Output:

headers={'x-api-key':'09ba90f6-dcd0-42c0-8c13-5baa6f2377d0'} print headers

Output:

resp = requests.get(url,headers=headers) print resp.status_code

Here you will get the output code as status code as 200.

print resp.content print resp

The above will print the content.

From the above code snippets, we need to first import the request library, and then we create a URL, and we will print the URL, and headers will also be defined and printed. Then we saw that request.get() method is called by passing the URL and headers obtained above to this method. This method returns a response object (resp). In the above code snippets, we can see that we will be printing the content of the request using this response object.get() method which will allow us to access and print the status_code and entire content is printed, and we can also see the list of attributes of this response object that are available. Similarly, we also can use different request methods like requests.put(), request.post(), request.delete(), etc.

We can see the syntax of each of these request methods, and we can see below:

Call.request.get(URL) this is used to send a GET request to the URL.

Call.request.post(URL, data= dict) in this dict contains a dictionary of keys and also has values to send to a POST request.

Call.request.put(URL, data =dict) this also works similarly to POST request; this will also send URL and values to a PUT request.

Call.requset.delete(URL, data =dict); this also has the same parameters as the above two request methods, and this request also sends the URL and values to the DELETE request method.

In Python, we use PycURL as a CURL tool and are used for testing REST APIs. As this PycURL supports a different variety of protocols like FILE, FTPS, HTTPS, IMAP, SMB, SCP, etc. The installation of PycURL is very simple for any of the operating systems. So below is the sampling process for installing the PycURL.

$ pip install pycurl $ easy_install pycurl

The above two can be used for installing pycurl in mac or Linux OS. Now we will see how can this be installed in Windows OS, but before this, we need to install a few dependencies. So you can run the below command in the Python terminal as below:

Command:

$ pip install pycurl

If pip is not used, we can use EXE and MSI installers available at PycURL windows.

Example #2

Let us below the sample example for sending an HTTP GET request.

Code:

import pycurl from io import BytesIO b_obj = BytesIO() crl = pycurl.Curl() crl.setopt(crl.WRITEDATA, b_obj) crl.perform() crl.close() get_body = b_obj.getvalue() print('Output of GET request:n%s' % get_body.decode('utf8'))

Output:

Similarly, there are different ways and codes in Python using PycURL for using POST, PUT, DELETE, etc., methods. Let us what code sample can be written for sending an HTTP DELETE request. This method where it deletes the server resource that is identified by the URL. This can be implemented using CUSTOMREQUEST.

Example #3

Below is a sample example:

Code:

import pycurl crl = pycurl.Curl() crl.setopt(crl.CUSTOMREQUEST, "DELETE") crl.perform() crl.close()

The above code snippet is to send the HTTP DELETE request. So we can see how to use HTTP DELETE request for sending this request using a curl tool in Python like PycURL.

Conclusion

In this article, we discussed the curl, which is a tool for transferring data from and to the server. In Python, we have the PycURL library, which uses libcurl, a standard library, and PycURL uses its values. We also saw the various methods that are called syntax. In this article, we also saw the usage of PycURL, which we first saw how to import it and how to use this and use various curl methods such as perform(), close(), etc.

Recommended Articles

We hope that this EDUCBA information on “Python Curl” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

10 Text Functions In Excel With Examples

Excel is all about working with numbers. However, if your data consists of too much text, you don’t have to worry at all. Excel provides several functions that make it easier to manipulate text strings. These functions let you easily find a string, count the characters in a string, remove extra spaces from a string, join two or more strings, and perform other similar tasks on the textual data.

What are Text functions in Excel?

Text Functions are Microsoft Excel’s native functions that allow transforming or analyzing textual data. Excel provides a total of 30+ Text functions and many of these are often used by people for data analysis. This post highlights 10 such Text functions, with their uses and examples.

10 Text Functions in Excel with Examples

Following is the list of top 10 functions in Excel:

FIND

LEN

LEFT

RIGHT

MID

SUBSTITUTE

UPPER

TRIM

CONCATENATE

TEXT

Let’s take a detailed look at these functions, one by one.

1] FIND

The FIND function allows you to find a text string within another. It returns the position at which a character or string begins within another text string.

Syntax 

FIND(find_text, within_text, [start_num])

find_text argument is used to enter the text the user wants to search.

within-text argument takes the text which contains the text that needs to be found.

[start_num] is an optional argument that takes the position from where to start the search. It takes the value 1 by default.

Example

Let us say the A3 cell in an Excel sheet contains the string ‘The Windows Club’. If the user wants to find the position of ‘Win’ within the string, he may use the ‘Find’ functions as:

f(x)=FIND("Win", A1)

The output of the above function will be 5, as 5 represents the starting position of the text ‘Win’ within ‘The Windows Club’.

Note: The FIND function is case-sensitive. If you do not want to match the case, you can use the SEARCH function, which has the same syntax as the FIND function.

Read: How to use the new TEXTSPLIT function in Excel

2] LEN

The LEN function calculates the length of the string, i.e. the number of characters present in a string. It counts the spaces as characters.

Syntax 

LEN(text)

text argument takes the string whose length the user wants to find.

Example

In the above example, if the user wants to find the length of the string ‘The Windows Club’, he may use the ‘LEN’ function as:

f(x)=LEN (A3)

The output of the above function will be 16, as there are 16 characters in the string ‘The Windows Club’, including spaces.

Also read: Arrows keys are not working in Microsoft Excel.

3] LEFT

The LEFT function returns several successive characters from the left side of a string, based on the number specified by the user.

Syntax 

LEFT(text, [num_chars])

text argument is used to specify the string that contains the characters that need to be found.

[num_chars] specifies the number of characters to be extracted from the left of the main string. This argument is optional. It takes ‘1’ as a default value, if not specified by the user.

Example

In the same example as stated above, if the user wants to extract the first 7 characters from ‘The Windows Club’, he may use the ‘LEFT’ function as:

f(x)=LEFT (A3, 7)

The output of the above function will be The Win, as these are the 7 leftmost characters in the string ‘The Windows Club’, including spaces.

4] RIGHT

The RIGHT function is used to extract several characters from the extreme right of a string.

Syntax 

RIGHT(text, [num_chars])

text argument specifies the string that contains the desired characters.

[num_chars] argument specifies the number of characters that need to be extracted, moving from the extreme right to the left of the string. This is an optional argument that takes ‘1’ as the default value if left unspecified.

Example

Taking the same example, if the user wants to extract the last 7 characters from the string ‘The Windows Club’, he may use the ‘RIGHT’ function as:

f(x)=RIGHT(A3, 7)

The output of the above function will be ws Club, since they are the 7 rightmost characters in ‘The Windows Club’, including spaces.

5] MID

The MID function returns several consecutive characters or a substring from the middle of another string.

Syntax 

MID(text, start_num, num_chars)

text argument takes the string that contains the desired characters.

start_num argument takes the position from where to start extracting the characters.

num_chars argument takes the number of characters the user wants to extract from the string.

Example

In the above example, if the user wants to extract 4 characters starting from the 3rd character in the string ‘The Windows Club’, he may use the ‘MID’ function as:

f(x)=MID(A3, 3, 4)

The output of the above function will be e Wi, as ‘e’ is the third character and staring from ‘e’ counting spaces as well, ‘e Wi’ are the 4 consecutive characters in the string ‘The Windows Club’.

6] SUBSTITUTE

The Substitute function replaces an existing text with a new text in a given string.

Syntax 

SUBSTITUTE(text, old_text, new_text, [instance_num])

text argument specifies the main string.

old_text argument specifies the text that needs to be replaced.

new_text argument specifies the text that needs to be put in place of the existing text.

[instance_num] argument specifies which instance (or occurrence) of the existing text is to be replaced. This is an optional argument. If you specify this value, only that instance of the text will be replaced; otherwise, all the instances of the existing text will be replaced with the new text.

Example

In the same example, if the user wants to substitute ‘Welcome to The’ for ‘The’ in ‘The Windows Club’, he may use the ‘SUBSTITUTE’ function as:

f(x)=SUBSTITUTE(A3, "The", "Welcome to The")

The output of the above function will be Welcome to The Windows Club, as the substitute function has replaced ‘The’ with ‘Welcome to The’ in the text string ‘The Windows Club’.

7] UPPER

The UPPER function converts a string into uppercase, i.e., it returns a string after capitalizing each letter.

Syntax 

UPPER(text)

text argument takes the string that needs to be capitalized.

Example

Following the same example, if the user wants to capitalize each letter in the string ‘The Windows Club’, he may use the ‘UPPER’ function as:

f(x)=UPPER(A3)

The output of the above function will be THE WINDOWS CLUB.

Note:

If you want to convert a string into lowercase, you may use the LOWER function, having the same syntax as that of the UPPER function.

If you want to capitalize the first letter of each word in a string, you may use the PROPER function with the same syntax.

8] TRIM

The TRIM function removes all the extra spaces within a string, leaving just 1 space between two words.

Syntax 

TRIM(text)

text argument takes the string with irregular spacing.

Example

In the example stated above, if the user wants to remove unnecessary spaces from the string ‘The      Windows        Club’, he may use the ‘TRIM’ function as:

f(x)=TRIM(A3)

The output of the above function will be The Windows Club, leaving just a single space between words.

9] CONCATENATE

The CONCATENATE function joins two or more strings in Excel.

Syntax 

CONCATENATE(text1, [text2], ...)

text1 argument is mandatory. It takes the first string to join.

text2 argument takes the additional string to join. You may join up to 255 strings.

Example

Let us say the A3 cell in an Excel sheet contains the string ‘The’, the A4 cell contains the string ‘Windows’, and the A5 cell contains the string ‘Club’. If the user wants to join these strings, he may use the ‘CONCATENATE’ functions as:

f(x)=CONCATENATE(A3, " ", A4, " ", A5)

The output of the above function will be The Windows Club, joining the strings in A3, A4, and A5 cells with spaces between these strings.

Tip: Use the ampersand (&) symbol to concatenate two text strings.

10] TEXT

The TEXT function converts the format of a number from ‘numeric’ to ‘text’. The function can be used to place formatted numbers between text.

Syntax 

TEXT(value, format_text)

value argument takes the numerical value that needs to be formatted.

format_text argument takes the format that needs to be applied to the value.

Example

Let us say the A2 cell in Excel contains the string ‘The Windows Club started on’ and the A3 cell contains the numeric data ’20-04-2009′; the two of these can be combined in a single sentence using the ‘CONCATENATE’ and the ‘TEXT’ functions as:

f(x)=A2&" "&TEXT(A3,"mmmm d, yyyy")&"."

The output of the above functions will be The Windows Club started on April 20, 2009.

Also read: How to convert currencies in Excel.

What is an example of a text function?

The TEXT function in Excel is used to join a formatted number with a text string. For example, if an Excel sheet contains the string ‘Retails sales surge by’ in cell A1, and the number ‘20000’ in cell A2, then TEXT function can be used to join the content of these two cells as:

f(x)=A1&" "&TEXT(A3,"$ ##,###")&".".

The above function will return ‘Retails sales surge by $20,000.’, where the number 20000 has been formatted using a currency symbol and comma separator.

What is the use of lower function?

The LOWER function is used to change the case of a string to lowercase. If a given string is in uppercase, proper case, or sentence case, the LOWER function will return the string with each of its alphabet converted in small letters. The syntax for LOWER function is LOWER(text), where text specifies the string or reference to the cell that contains the string that needs to be converted into lowercase.

Read Next: Top 15 Financial functions in Microsoft Excel.

How Println Works In Kotlin With Examples?

Introduction to Kotlin println

Web development, programming languages, Software testing & others

Syntax

The kotlin language uses many default keywords, variables, and functions to implement the mobile-based applications, with some pre-defined keywords, including the functions. Like that, println() is the default function for handling and print the statements, which the coder declares.

{ val variablename= values println(“coder statements and ${variablename}””) var var2= values println(“coder statements and $var2”) }

The above codes are the basic syntax for utilising the println() method and its statements used by the kotlin language. Then, based on the user scenario, we can print the outputs on the console screen.

How does println work in Kotlin?

Using the println() method, the coder prints the statements and the outputs the programmer enters, and it depends on the application point of view. The programmer entered all the codes like keywords, variables, functions, and classes that have both primary and secondary classes. Some nested classes concept implements the parent class with the child class, and then it’s called by the specific packages. For each method, both default and customized methods used the println() statements.

The println() method has similar to the print() method but some difference is there like print() method prints the string inside of the quotes and println() method print the strings inside the quotes which is similar like print() method but the mouse cursor which automatically moves to the next line of the console screen. We can use the expressions and catch the exceptions and errors instance whenever it requires like the try-catch statement is used for handling the exceptions block, but the catch and finally blocks to capture and print the exceptions using the print and println() method. And also, when we want to print the variable inside the println() method, we can use the dollar($) symbol followed by either var and val names along with inside of the double-quoted string literals.

Examples of Kotlin println

Given below are the examples of Kotlin println:

Example #1

Code:

import java.util.Scanner class examp1{ fun demo() { val strinp="Welcome To My Domain its the first example that related to the kotlin println() statement" mlist.add("Please add the first input") mlist.add("Please add the second input") mlist.add("Please add the third input") mlist.add("Please add the fourth input") mlist.add("Please add the fifth input") println("Please follow the below loop iteration") for(vlist in mlist){ println(vlist) } println("Thank you users your mutablelist datas are entered successfully") println(mlist[1]) mlist.add(1,"June") println("We can modify the first mutable list value as mlist.add(1,"June")") for(vlist in mlist){ println(vlist) } mlist.add("July") println("Again we can add one more list values mlist.add("July")") for(vlist in mlist){ println(vlist) } mlist.addAll(2,finp1) println("We can add all the list values into the single list: mlist.addAll(1,finp1)") for(vlist in mlist){ println(vlist) } mlist.addAll(finp) println("We can add all the values and make it to the single list: mlist.addAll(finp)") for(vlist in mlist){ println(vlist) } mlist.remove("July") println("We can remove the specified values: mlist.remove("July")") for(vlist in mlist){ println(vlist) } } } val num = 41.83 println("Your input num is:") println("$num") println("num = $num") println("${num + num}") println(41.83) val sc = Scanner(System.`in`) print("Please enter your input number: ") var il:Int = sc.nextInt() println("You entered input is: $il") var ob=examp1() ob.demo() }

Output:

Example #2

Code:

import java.util.Date import java.text.SimpleDateFormat class Exam2() { var id: Int = 0 var sname: String = "" var city: String = "" fun demo2(){ val sinp="41,Sivaraman, Chennai" println(sinp) } } enum class Second(var sec: String) { demo("Welcome To My Domain its the second example that related to the kotlin println()"){ override fun sample() { println("Thank you users have a nice day") } }, demo1("We can override the sample method"){ override fun sample() { println("Current month is june") } }, demo2("Again we override the sample method"){ override fun sample() { println("Next month is july") } }; abstract fun sample() fun demo1(svalues: String): String{ return "Have a Nice day users" } } val inp1 = Exam2() var sinp=inp1.demo2() println(SimpleDateFormat("yyyy-MM-ddX").parse("2024-06-22+00")) println("Welcome To My Domain its the second example that related to the kotlin println() method, $sinp") println("Hello users") println(41) println(1234567L) println(0b01001111) println(41.32) println(41.762F) println('a') println(true) println() var st = "Hello users thank you for spenting ur time with us" println(st) println(st) }

Output:

In the second example, we used the date format package utilised in the kotlin codes with some operations like integer, string, float, double and boolean datatype values printed on the output console.

Example #3 import java.util.Scanner try { val inpread = Scanner(System.`in`) println("Welcome To My Domain its the third example that related to the kotlin println()") println("Please enter your inputs") var id = inpread.nextInt() println("Your input id is "+id) demo(41,83,lamb) val inpdata = 12 / 4 println(inpdata) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executed whenever try is executing") } println("Have in Nice Day users please try again") } val result = in1 + in2 println(result) }

Output:

In the final example, we used the try-catch block for handling the exceptions and performed the arithmetic operations using the lambda expressions.

Conclusion

In kotlin language, we used many default methods, classes, and keywords to implement the application. So all the programming logic will be implemented using some codes like classes and methods eventhough some additional operations are performed, results are printed on the output console by using the print() and println() methods.

Recommended Articles

This is a guide to Kotlin println. Here we discuss the introduction, syntax, and working of println in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –

Update the detailed information about Polymorphism In Python With Examples on the Cancandonuts.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!