Python – AppDividend https://appdividend.com Latest Code Tutorials Mon, 22 Jul 2019 06:36:22 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Python – AppDividend https://appdividend.com 32 32 Python bin Example | bin() Function In Python Tutorial https://appdividend.com/2019/07/22/python-bin-example-bin-function-in-python-tutorial/ https://appdividend.com/2019/07/22/python-bin-example-bin-function-in-python-tutorial/#respond Mon, 22 Jul 2019 06:34:49 +0000 http://localhost/wordpress/?p=9976 Python bin Example | bin() Function In Python Tutorial

Python bin Example | bin() Function In Python Tutorial is today’s topic. Converting a decimal to binary is always an important function that is required in competitive programming as well. The bin() function returns a binary representation of an integer as the string. Using the bin() reduces the time required to code and also removes the […]

The post Python bin Example | bin() Function In Python Tutorial appeared first on AppDividend.

]]>
Python bin Example | bin() Function In Python Tutorial

Python bin Example | bin() Function In Python Tutorial is today’s topic. Converting a decimal to binary is always an important function that is required in competitive programming as well. The bin() function returns a binary representation of an integer as the string. Using the bin() reduces the time required to code and also removes the hassle.

Python bin Example

See the Python bin() function syntax.

bin(number)

The function bin() takes the number as a parameter which is converted to the binary number. If the number is not an integer, then __index__() method is implemented to return the integer.

See the following code example.

print("Binary of Eleven is:", bin(11))

See the following output.

➜  pyt python3 app.py
Binary of Eleven is: 0b1011
➜  pyt

As you can see in the example above, the bin() function returns the equivalent binary number prefixed with 0b of an integer.

If you don’t want that prefixed 0b, you can use the format() function.

print(format(11, 'b'))

See the following output.

➜  pyt python3 app.py
1011
➜  pyt

#Convert an object to binary implementing __index__() method

See the following example in which we implement the object to the binary implementing __index__() method.

class Add:
    a = 11
    b = 19

    def __index__(self):
        return self.a + self.b


app = Add()
print('Equivalent binary number is:', bin(app))

See the following output.

➜  pyt python3 app.py
Equivalent binary number is: 0b11110
➜  pyt

That is how the __index__() function is used to return an integer when we don’t have an integer as an argument in the Python bin() function.

More Examples

See the following example.

a = 11
b = bin(a)
print(type(b))
print(bin(a))

See the output.

➜  pyt python3 app.py
<class 'str'>
0b1011
➜  pyt

The bin() method is available and compatible with both the Python version Python 2.x and 3.x.

#Python bin() with float

See the following code example of the bin() with the float.

a = 11.19
print(bin(a))

See the following output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(bin(a))
TypeError: 'float' object cannot be interpreted as an integer
➜  pyt

So, Python bin() function can be used with the integers having different formats such as an octal, hexadecimal too. The function will take care of converting them into the binary string.

That’s all for python bin() function to convert an integer to the binary string. We also learned that an Object could also be converted to the binary string representation by implementing __index__() function that returns an integer.

Finally, Python bin Example | bin() Function In Python Tutorial is over.

The post Python bin Example | bin() Function In Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/22/python-bin-example-bin-function-in-python-tutorial/feed/ 0
Python ascii() Example | ascii() Function Tutorial https://appdividend.com/2019/07/20/python-ascii-example-ascii-function-tutorial/ https://appdividend.com/2019/07/20/python-ascii-example-ascii-function-tutorial/#respond Sat, 20 Jul 2019 09:41:45 +0000 http://localhost/wordpress/?p=9962 Python ascii() Example | ascii() Function Tutorial

Python ascii() Example | ascii() Function Tutorial is today’s topic. Python ascii() returns a string containing a printable representation of an object and it escapes the non-ASCII characters in the string using \x, \u or \U escapes. The ascii() function returns a readable version of any object like Strings, Tuples, Lists, etc. The ascii() function […]

The post Python ascii() Example | ascii() Function Tutorial appeared first on AppDividend.

]]>
Python ascii() Example | ascii() Function Tutorial

Python ascii() Example | ascii() Function Tutorial is today’s topic. Python ascii() returns a string containing a printable representation of an object and it escapes the non-ASCII characters in the string using \x, \u or \U escapes. The ascii() function returns a readable version of any object like Strings, Tuples, Lists, etc. The ascii() function will replace any non-ascii characters with escape characters: å will be replaced with \xe5.

Python ascii() Example

Earlier in Python2, repr() method was used to return a printable representation of the object, but it didn’t escape the non-ASCII characters.

For example, ë is represented as ë by repr()  method, but by ascii() method, it is represented by the Python escape sequence \xeb. Similarly, ö is represented as ö by repr() and \xf6n by ascii()method.

The syntax of the ascii() function is following.

ascii(object)

Now, see the following code example.

print(ascii("¥"))

print(ascii("µ"))

print(ascii("Ë"))

See the following output.

➜  pyt python3 app.py
'\xa5'
'\xb5'
'\xcb'
➜  pyt

So, It returns a string containing the printable representation of an object.

#Python ascii function example with list and tuple

Okay, let’s see the following example of list and tuple.

# app.py

tup = ("Ë", "¥", "Ä")
print(ascii(tup))

list = ['Facebook', 'FaceBöök']
print(ascii(list))

See the following output.

➜  pyt python3 app.py
('\xcb', '\xa5', '\xc4')
['Facebook', 'FaceB\xf6\xf6k']
➜  pyt

#How to get an ASCII value of the character

Python function ord() would get an int value of a char. And if you want to convert back after playing with that number, function chr() does the trick for you.

See the following code example.

print(ord('k'))
print(chr(97))
print(chr(ord('j') + 3))

See the output.

➜  pyt python3 app.py
107
a
m
➜  pyt

Note that ord() function doesn’t give you a ASCII value per se; it gives you a numeric value of that character in whatever encoding it’s in.

Therefore the result of the ord('ä') can be 228 if you’re using Latin-1, or it can raise a TypeError if you’re using the UTF-8. It can even return a Unicode codepoint instead if you pass it a Unicode.

Finally, Python ascii() Example | ascii() Function Tutorial is over.

The post Python ascii() Example | ascii() Function Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/20/python-ascii-example-ascii-function-tutorial/feed/ 0
Python Strings Example | String In Python Tutorial https://appdividend.com/2019/07/20/python-strings-example-string-in-python-tutorial/ https://appdividend.com/2019/07/20/python-strings-example-string-in-python-tutorial/#respond Sat, 20 Jul 2019 08:25:12 +0000 http://localhost/wordpress/?p=9945 Python Strings Example | String In Python Tutorial

Python Strings Example | String In Python Tutorial is today’s topic. In Python, Strings are the arrays of bytes representing the Unicode characters. Python does not have the character data type, and a single character is simply a string with a length of 1. #What is String in Python A string is the sequence of characters. A […]

The post Python Strings Example | String In Python Tutorial appeared first on AppDividend.

]]>
Python Strings Example | String In Python Tutorial

Python Strings Example | String In Python Tutorial is today’s topic. In Python, Strings are the arrays of bytes representing the Unicode characters. Python does not have the character data type, and a single character is simply a string with a length of 1.

#What is String in Python

A string is the sequence of characters.

A character is simply the symbol. For example, an English language has 26 characters.

Computers do not deal with characters, and they deal with binary numbers. Even though you may see the characters on your screen, internally, it is stored and manipulated as the combination of 0’s and 1’s.

The conversion of character to the number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the simplified encoding used.

You can count the characters in one string using the Python len() function.

Python Strings Example

In Python, the string is the sequence of the Unicode character.

Unicode was introduced to include every character in all the languages and bring uniformity in encoding.

Like many other programming languages, strings in Python are the arrays of bytes representing Unicode characters.

However, Python does not have the character data type, and a single character is simply the string with a length of 1.

Square brackets can be used to access the items of a string.

#How to create a string in Python

Python Strings can be created using the single quotes or double quotes or even the triple quotes.

String in the single quotes cannot hold any other single-quoted character in it; otherwise, an error arises because a compiler won’t be able to recognize where to start and end the string.

If we want to overcome this error, the use of double quotes is preferred, because it helps in the creation of Strings with a single quotes in them.

For strings which contain the Double quoted words in them, use of triple quotes is suggested. Along with this, triple quotes also allow a creation of multiline strings.

See the following examples of String literals.

print("Millie Bobby Brown")
print('Millie Bobby Brown')
print('''Millie Bobby Brown''')

We can use single and double quote.

➜  pyt python3 app.py
Millie Bobby Brown
Millie Bobby Brown
Millie Bobby Brown
➜  pyt

We can display the string literal with the print() function.

In the above example, we have used single, double, and triple quotes. We will get the same output, but the triple quote is useful when we have Double quoted words as a string. See the following code.

print('''Mill's ''')

See the following output.

➜  pyt python3 app.py
Mill's
➜  pyt

#Multiline Strings

You can assign a multiline string to a variable by using three quotes. See the following code.

muldata = """Eleven's character Played
by Millie Bobby Brown is the 
best thing that ever happened in the
Drama Series."""
print(muldata)

See the following output.

➜  pyt python3 app.py
Eleven's character Played
by Millie Bobby Brown is the
best thing that ever happened in the
Drama Series.
➜  pyt

#Accessing characters in Python

We can access the characters of Python using index just like arrays in Programming languages.

In Python, individual characters of the String can be accessed by using a method of Indexing, to access the range of characters in the String, method of slicing is used.

Slicing in the String is done by using the Slicing operator (colon). Indexing allows negative address references to access the characters from the back of a String, e.g., -1 refers to a last character, -2 refers to a second last character and so on.

While accessing the index out of the range will cause the IndexError. Only Integer datatypes are allowed to be passed as the index, float, or other types will cause a TypeError.

See the following code example.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ", StrA)
print("\nFirst character of String is: ", StrA[0])
print("\nLast character of String is: ", StrA[-1])
print("\nSlicing characters from 3-12: ", StrA[3:12])
print("\nSlicing characters between " + "3rd and 2nd last character: ", StrA[0:-5])

See the following output.

➜  pyt python3 app.py
Initial String:  MillieBobbyBrown

First character of String is:  M

Last character of String is:  n

Slicing characters from 3-12:  lieBobbyB

Slicing characters between 3rd and 2nd last character:  MillieBobby
➜  pyt

#Deleting/Updating from a String

In Python, Updation or deletion of the characters from the string is not allowed. It will cause an error because item assignment or item deletion from the String is not supported.

Although deletion of the entire String is possible with the use of the built-in del keyword, it is because Strings are immutable, hence elements of the String cannot be changed once it has been assigned.

Only new strings can be reassigned to that same name.

Now, let’s try to update the string, although we know that we will get some error.

See the following code example.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

StrA[2] = 'K'
print("\nUpdating character at 2nd Index: ") 
print(StrA)

Okay, so we are trying to modify the StrA. Now, see the following output.

➜  pyt python3 app.py
Initial String:
MillieBobbyBrown
Traceback (most recent call last):
  File "app.py", line 5, in <module>
    StrA[2] = 'p'
TypeError: 'str' object does not support item assignment

Now, delete the string using the del keyword.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

del StrA
print(StrA)

See the following output.

➜  pyt python3 app.py
Initial String:
MillieBobbyBrown
Traceback (most recent call last):
  File "app.py", line 6, in <module>
    print(StrA)
NameError: name 'StrA' is not defined
➜  pyt

See, after we have removed the StrA, it is now saying that StrA is not defined.

#Formatting of Strings

We can format the string using the Python String format() method.

Python String format() method takes any number of arguments. But, it is mainly divided into the two types of parameters which are following.

  1. Positional parameters – It is a list of parameters that can be accessed with an index of a parameter inside the curly braces {index}.
  2. Keyword parameters – It is a list of the parameters of type key=value that can be accessed with the key of a parameter inside curly braces {key}.

See the following example.

# app.py

name = 'Millie'
coins = 15
print('Hello {}, you are {} years old.'.format(name, coins))

See the following output.

name = 'Millie'
coins = 15
print('Hello {}, you are {} years old.'.format(name, coins))

Python String strip() method removes any whitespace from the beginning of the end.

See the following code example.

name = "      Millie   "
print(name.strip())

See the following output.

➜  pyt python3 app.py
Millie
➜  pyt

Finally, Python Strings Example | String In Python Tutorial is over.

The post Python Strings Example | String In Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/20/python-strings-example-string-in-python-tutorial/feed/ 0
Python any() Function Example | any() Method Tutorial https://appdividend.com/2019/07/20/python-any-function-example-any-method-tutorial/ https://appdividend.com/2019/07/20/python-any-function-example-any-method-tutorial/#respond Sat, 20 Jul 2019 05:16:55 +0000 http://localhost/wordpress/?p=9930 Python any() Function Example | any() Method Tutorial

Python any() Function Example | any() Method Tutorial is today’s topic. Python any() function returns True if any element of an iterable is True. If not, any() returns False. If the iterable object is empty, the any() function will return False. The any() function is the opposite of all() function. An iterator is an object […]

The post Python any() Function Example | any() Method Tutorial appeared first on AppDividend.

]]>
Python any() Function Example | any() Method Tutorial

Python any() Function Example | any() Method Tutorial is today’s topic. Python any() function returns True if any element of an iterable is True. If not, any() returns False. If the iterable object is empty, the any() function will return False. The any() function is the opposite of all() function. An iterator is an object that contains the countable number of values. Python iterator is an object that can be iterated upon, meaning that you can traverse through all the values inside an iterator.

Python any() Function

The syntax of any() is following.

any(iterable)

Python any() method takes an iterable in Python. Those iterables are Python List, Python Dictionary, or Python Tuple.

The any() method returns following values.

  1. True if at least one item of an iterable is True.
  2. False if all items are false or if an iterable is empty.

#Any() method with Python Dictionary

See the following code.

dictA = {0: 'False', 1: 'False'}
print(any(dictA))

dictB = {1: 'True', 21: 'True'}
print(any(dictB))

dictC = {1: 'True', False: 0}
print(any(dictC))

dictD = {}
print(any(dictD))

dictE = {'0': 'True'}
print(any(dictE))

dictF = {0: 'True'}
print(any(dictF))

See the following output.

➜  pyt python3 app.py
True
True
True
False
True
False
➜  pyt

In Dictionary, the any() function checks only dictionary keys and not the values. Values do not matter if they are True or False.

In the above examples, you can see that, if any dictionary key’s value is 1 or True then it returns True.

If either dictionary is empty or all the keys are either 0 or False, then it will return False.

#Any() method with Python List

Let’s take an example of Python List iterator with any() method.

# app.py

listA = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print(any(listA))

listB = []
print(any(listB))

listC = [1, 0]
print(any(listC))

listD = [0, False]
print(any(listD))

Now, see the output.

➜  pyt python3 app.py
True
False
True
False
➜  pyt

So, same as the dictionary, if any of the list values are 1 or True, or any value except 0 or False, then it will return True.

If all the list is empty or all the values are either 0 or False, then it returns False.

#Any() method with Python String

Let’s check the String iterator with any() method.

# app.py

strA = 'Millie Bobby Brown'
print(any(strA))

strB = ''
print(any(strB))

See the following output.

➜  pyt python3 app.py
True
False
➜  pyt

From the above string examples, we can say that if the string is empty, then it will return False otherwise it returns True.

#Any() method with Python Tuple

Let’s take an example of Python tuple iterator with any() method.

# app.py

tupA = ('Millie Bobby Brown', 'Finn Wolfhard', 'Noah Schnapp')
print(any(tupA))

tupB = ()
print(any(tupB))

tupC = (0, False)
print(any(tupC))

tupD = (1, False)
print(any(tupD))

tupE = ('0', 'False')
print(any(tupE))

See the following output.

➜  pyt python3 app.py
True
False
False
True
True
➜  pyt

So, it returns True if any of the elements is True. It returns False if tuple is empty or all are False or 0 values.

Any() method can be thought of as a sequence of OR operations on the provided iterables.

We can roughly think of any() and all() as a series of logical or and and operators, respectively.

#Truth table

+-----------------------------------------+---------+---------+
|                                         |   any   |   all   |
+-----------------------------------------+---------+---------+
| All Truthy values                       |  True   |  True   |
+-----------------------------------------+---------+---------+
| All Falsy values                        |  False  |  False  |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| Empty Iterable                          |  False  |  True   |
+-----------------------------------------+---------+---------+

One important thing to know about any() and all() method is, it will short-circuit entire execution, the moment they know the output. The advantage is whole iterable need not be consumed.

Here’s the Python implementation of any() and all() are following.

def any(iterable):
    for i in iterable:
        if i:
            return True
    return False # for an empty iterable, any returns False!

def all(iterable):
    for i in iterable:
        if not i:
            return False
    return True  # for an empty iterable, all returns True!

Finally, Python any() Function Example | any() Method Tutorial is over.

The post Python any() Function Example | any() Method Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/20/python-any-function-example-any-method-tutorial/feed/ 0
Python all() Function Example | Python all() Tutorial https://appdividend.com/2019/07/18/python-all-function-example-python-all-tutorial/ https://appdividend.com/2019/07/18/python-all-function-example-python-all-tutorial/#respond Thu, 18 Jul 2019 11:43:33 +0000 http://localhost/wordpress/?p=9869 Python all() Function Example | Python all() Tutorial

Python all() Function Example | Python all() Tutorial is today’s topic. The all() method returns True when all items in the given iterable are true. If not, it returns False. If the iterable object is empty, the all() function also returns True. Python all() Function The syntax of Python all() method is following. all(iterable) The […]

The post Python all() Function Example | Python all() Tutorial appeared first on AppDividend.

]]>
Python all() Function Example | Python all() Tutorial

Python all() Function Example | Python all() Tutorial is today’s topic. The all() method returns True when all items in the given iterable are true. If not, it returns False. If the iterable object is empty, the all() function also returns True.

Python all() Function

The syntax of Python all() method is following.

all(iterable)

The all() method takes a single parameter. An iterable parameter is an object which can be list, tuple, or dictionary.

The all() method returns:

  1. True – If all the items in an iterable are True.
  2. False – If any item in an iterable is False.
When Return Value
All values are true True
All values are false False
One value is true (others are false) False
One value is false (others are true) False
Empty Iterable True

#The all() function for Python List

Let’s test the all() function for Python List.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print(all(listB))

See the following output.

➜  pyt python3 app.py
True
➜  pyt

Let’s check for the empty iterable.

# app.py

listB = []
print(all(listB))

See the output.

➜  pyt python3 app.py
True
➜  pyt

Let’s take the false values inside the list and check the output.

# app.py

listB = [0, False]
print(all(listB))

See the following output.

➜  pyt python3 app.py
False
➜  pyt

Let’s take one of the value as a false.

# app.py

listB = [21, 19, 18, 0]
print(all(listB))

See the output.

➜  pyt python3 app.py
False
➜  pyt

#The all() function for Python Strings

Strings are also iterators in Python. So, let’s test with all() function.

# app.py

strB = 'MillieBobbyBrown'
print(all(strB))

See the output.

➜  pyt python3 app.py
True
➜  pyt

See other examples.

# app.py

strC = '02119'
print(all(strC))

strD = ''
print(all(strD))

See the output.

➜  pyt python3 app.py
True
True
➜  pyt

#The all() function for Python Dictionary

In case of dictionaries, if all the keys (not values) are True or a dictionary is empty, all() returns True. Else, it returns the False value for all other cases.

See the following code example.

dictA = {0: 'False', 1: 'False'}
print(all(dictA))

dictB = {1: 'True', 21: 'True'}
print(all(dictB))

dictC = {1: 'True', False: 0}
print(all(dictC))

dictD = {}
print(all(dictD))

dictE = {'0': 'True'}
print(all(dictE))

Okay, so in the above code, if the keys are either 0 or False, then the output will be False. 

#Python’s any() and all() functions

The function any() and all(), both look for the condition that allows them to stop evaluating.

Here’s the Python implementation of any() and all() functions.

def any(iterable):
    for i in iterable:
        if i:
            return True
    return False # for an empty iterable, any returns False!

def all(iterable):
    for i in iterable:
        if not i:
            return False
    return True  # for an empty iterable, all returns True!

Finally, Python all() Function Example | Python all() Tutorial is over.

The post Python all() Function Example | Python all() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/18/python-all-function-example-python-all-tutorial/feed/ 0
Python List Example | List In Python Tutorial Explained https://appdividend.com/2019/07/18/python-list-example-list-in-python-tutorial-explained/ https://appdividend.com/2019/07/18/python-list-example-list-in-python-tutorial-explained/#respond Thu, 18 Jul 2019 10:01:23 +0000 http://localhost/wordpress/?p=9853 Python List Example | List In Python Tutorial Explained

Python List Example | List In Python Tutorial Explained is today’s topic. There are four collection data types in the Python programming language: The list is the collection which is ordered and changeable. It allows duplicate members. A tuple is a collection which is ordered and unchangeable. It allows duplicate members. Set is the collection […]

The post Python List Example | List In Python Tutorial Explained appeared first on AppDividend.

]]>
Python List Example | List In Python Tutorial Explained

Python List Example | List In Python Tutorial Explained is today’s topic. There are four collection data types in the Python programming language:

  1. The list is the collection which is ordered and changeable. It allows duplicate members.
  2. A tuple is a collection which is ordered and unchangeable. It allows duplicate members.
  3. Set is the collection which is unordered and unindexed — no duplicate members.
  4. Dictionary is the collection which is unordered, changeable, and indexed. No duplicate members.

In this example, we will talk about Python List. A list is a collection which is ordered and changeable. In Python, lists are written with square brackets.

Python List

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. An important thing about a list is that items in a list need not be of the same type.

A list may contain duplicate values with their distinct positions, and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.

Let’s creating a list is as simple as putting different comma-separated values between square brackets. See the following code.

# app.py

listA = ['Game Of Thrones', 8, 'Stranger Things', 3, 'Friends', 10]
listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print(listA)
print(listB)

See the following output.

➜  pyt python3 app.py
['Game Of Thrones', 8, 'Stranger Things', 3, 'Friends', 10]
['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
➜  pyt

Similar to the string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

#Accessing Values in Python Lists

You access the list items by referring to the index number. See the following code.

# app.py

listA = ['Game Of Thrones', 8, 'Stranger Things', 3, 'Friends', 10]
listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print(listA[2])
print(listB[1])

See the following output.

➜  pyt python3 app.py
Stranger Things
Millie Bobby Brown
➜  pyt

In the above example, we have accessed the list items using their indices.

If we want to access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.

# app.py

listA = ['Game Of Thrones', 8, 'Stranger Things', 3, 'Friends', 10]
listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print("listA[2]: ", listA[2])
print("listB[1:2]: ", listB[1:2])

See the following output.

➜  pyt python3 app.py
listA[2]:  Stranger Things
listB[1:2]:  ['Millie Bobby Brown']
➜  pyt

#Updating Python Lists

If we want to change the value of a specific element, then we have to refer to the index number. See the following code.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print('Before change', listB)
listB[2] = 'Emma Mackey'
print('After change', listB)

See the following output.

➜  pyt python3 app.py
Before change ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
After change ['Emilia Clarke', 'Millie Bobby Brown', 'Emma Mackey']

#Loop Through a List

If we want to iterate through a list, then you can use the for loop. See the following code.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
for item in listB:
    print(item)

See the output.

➜  pyt python3 app.py
Emilia Clarke
Millie Bobby Brown
Jennifer Aniston
➜  pyt

#Check if Element Exists

We can check if the item exists inside the list or not using if condition. See the following code.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
if "Millie Bobby Brown" in listB:
    print('Millie is Stranger Things Star')

See the following output.

➜  pyt python3 app.py
Millie is Stranger Things Star
➜  pyt

#Python List Length

We can check the Python List length using the len() function. If we want to determine how many items a list has, use the len() method.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
print(len(listB))
See the following output.
➜  pyt python3 app.py
3
➜  pyt

Here, we get the output three because the list contains the three items.

#How To Add Items In Python List

We can use the Python List append() method to add the items in Python. We can add or append the new item in the list using the append() method. See the following code.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
listB.append('Emma Mackey')
print(listB)

See the following output.

➜  pyt python3 app.py
['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston', 'Emma Mackey']
➜  pyt

If we want to insert an element at the specified index, we can use the insert() method. See the following syntax of the insert() method.

insert(index, item)

See the following code example.

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
listB.insert(2, 'Emma Mackey')
print(listB)

See the following output.

➜  pyt python3 app.py
['Emilia Clarke', 'Millie Bobby Brown', 'Emma Mackey', 'Jennifer Aniston']
➜  pyt

See, we have inserted an element at the index 2. Remember, the index starts at 2.

#Remove Item from Python List

There are several methods to remove the item from Python List.

First, we will see the Python List pop() method.

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
listB.pop()
print(listB)

It will remove the last item from the list. So, in our case, Jennifer Aniston will be removed. See the following output.

➜  pyt python3 app.py
['Emilia Clarke', 'Millie Bobby Brown']
➜  pyt

Now, let’s see the Python List remove() method.

The Python remove() method removes the specified item from the list. We need to pass the item name.

# app.py

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
listB.remove('Emilia Clarke')
print(listB)

See the output.

➜  pyt python3 app.py
['Millie Bobby Brown', 'Jennifer Aniston']
➜  pyt

There is also one keyword called del, which also removes the item from the list. See the following example.

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
del listB[0]
print(listB)

See the output.

➜  pyt python3 app.py
['Millie Bobby Brown', 'Jennifer Aniston']
➜  pyt

The clear() method empties the list. See the following code.

listB = ['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
listB.clear()
print(listB)

See the output.

➜  pyt python3 app.py
[]
➜  pyt

#The list() Constructor

You can use the list() constructor to make a new list. See the following example.

# app.py

listB = list(('Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston'))
print(listB)

In the above code, we need to add double rounded brackets. See the following output.

➜  pyt python3 app.py
['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
➜  pyt

So, using the list() constructor to Make a List.

#Copy a List

You cannot copy a list by merely typing list2 = list1, because list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, and one way is to use the built-in List method copy().

See the following copy() method code example.

listB = list(('Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston'))
listM = listB.copy()
print(listM)

See the output.

➜  pyt python3 app.py
['Emilia Clarke', 'Millie Bobby Brown', 'Jennifer Aniston']
➜  pyt

#List Methods

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

Method Description
append() Adds an item at the end of the list.
clear() Removes all the items from the list.
copy() Returns the copy of the list.
count() Returns the number of items with the specified value.
extend() Add the items of a list (or any iterable), to the end of the current list.
index() Returns the index of the first item with the specified value.
insert() Adds an item at the specified position.
pop() Removes the item at the specified position.
remove() Removes the item with the specified value.
reverse() Reverses the order of a list.
sort() Sorts the list.

 

Finally, Python List Example | List In Python Tutorial Explained is over.

The post Python List Example | List In Python Tutorial Explained appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/18/python-list-example-list-in-python-tutorial-explained/feed/ 0
Python RegEx Tutorial With Example | Regular Expressions in Python https://appdividend.com/2019/06/10/python-regex-tutorial-with-example-regular-expressions-in-python/ https://appdividend.com/2019/06/10/python-regex-tutorial-with-example-regular-expressions-in-python/#respond Mon, 10 Jun 2019 11:56:38 +0000 http://localhost/wordpress/?p=8273 Python RegEx Tutorial With Example | Regular Expressions in Python

Python RegEx Tutorial With Example | Regular Expressions in Python is today’s topic. A RegEx, or Regular Expression, is the sequence of characters that forms the search pattern. RegEx can be used to check if the string contains the specified search pattern. The regular expression in a programming language is a unique text string used […]

The post Python RegEx Tutorial With Example | Regular Expressions in Python appeared first on AppDividend.

]]>
Python RegEx Tutorial With Example | Regular Expressions in Python

Python RegEx Tutorial With Example | Regular Expressions in Python is today’s topic. A RegEx, or Regular Expression, is the sequence of characters that forms the search pattern. RegEx can be used to check if the string contains the specified search pattern. The regular expression in a programming language is a unique text string used for describing a search pattern. It is beneficial for extracting information from text such as code, files, log, spreadsheets, or even documents. Now, let’s start a Python RegEx Tutorial with example.

Python RegEx Tutorial With Example

While using the regular expression, the first thing is to recognize that everything is essentially a character, and we are writing the patterns to match the specific sequence of characters also referred to as a string. The Ascii or Latin letters are those that are on your keyboards and Unicode is used to match a different text.

It includes the digits and punctuation and all the special characters like $#@!%, etc.

For instance, a regular expression could tell the program to search for a specific text from the string and then to print out the result accordingly. The phrase can include the following.

  1. Text matching
  2. Repetition
  3. Branching
  4. Pattern-composition etc.

#Python RegEx Module

We can import the Python re module using the following code.

import re
  1. re” module included with a Python primarily used for string searching and manipulation.
  2. Also used frequently for web page for “Scraping” or extract a large amount of data from websites.

#RegEx in Python

Search the string to see if it starts with “The” and ends with “Australia.”

# app.py

import re

data = "The rain in Australia"
x = re.search("^The.*Australia$", data)
if (x):
  print("YES! We have a match!")
else:
  print("No match")

See the output.

Python RegEx Tutorial With Example

 

You can see the return object from the search function.

# app.py

import re

data = "The rain in Australia"
x = re.search("^The.*Australia$", data)
print(x)

See the following output.

Python RegEx Module

 

#Python RegEx Functions

Python re module offers the set of functions that allows us to search the string for the match.

Function Description
findall Returns the list containing all matches
search Returns the Match object if there is a match anywhere in the string
split Returns the list where a string has been split at each match
sub It replaces one or many matches with a string

 

#Python RegEx findall() Method

Python findall() method returns a list containing all matches.

See the following code example.

# app.py

import re

data = "The rain in Australia"
x = re.findall("Aus", data)
print(x)

See the below output.

Python RegEx findall() Method

 

The list contains the matches in the order they are found. If no matches are found, the empty list is returned. The findall() method is case sensitive. See the following code.

# app.py

import re

data = "The rain in Australia"
x = re.findall("aus", data)
print(x)

See the output.

Regular Expressions in Python

 

#Python RegEx search() Method

The search() function searches the string for the match and returns the Match object if there is a match.

If there is more than one match, only the first occurrence of the match will be returned.

See the following code example.

# app.py

import re

data = "The rain in Australia"
pos = re.search("\s", data)
print("The first white-space character is located", pos.start())

See the following output.

Python RegEx search() Method

 

#Python RegEx split() Method

The split() function returns the list where the string has been split at each match.

Now, let’s split at each white-space character. See the following code.

# app.py

import re

data = "The rain in Australia"
result = re.split("\s", data)
print(result)
See the following output.
Python RegEx split() Method

You can control a number of occurrences by specifying the maxsplit parameter.

Let’s split the string only at the first occurrence.

# app.py

import re

data = "The rain in Australia"
result = re.split("\s", data, 1)
print(result)

See the output.

Python RegEx split() Method Tutorial

 

#Python RegEx sub() Method

The sub() function replaces the matches with a text of your choice.

Let’s replace every white-space character with the symbol ‘~~~’.

# app.py

import re

data = "The rain in Australia"
result = re.sub("\s", "~~~", data)
print(result)

See the output.

Python RegEx sub() Method

 

#Python Metacharacters

Metacharacters are characters with a special meaning, which is the following.

Character Description Example
[] A set of characters “[a-m]”
\ Signals the special sequence (can also be used to escape special characters) “\d”
. Any character (except newline character) “he..o”
^ Starts with “^hello”
$ Ends with “world$”
* Zero or more occurrences “aix*”
+ One or more occurrences “aix+”
{} Exactly the specified number of occurrences “al{2}”
| Either or “falls|stays”
() Capture and group

 

#Python Special Sequences

A particular sequence is a \ followed by one of the characters in the list below and has a special meaning.

Character Description Example
\A Returns the match if the specified characters are at the beginning of the string “\AThe”
\b Returns the match where the specified characters are at the beginning or the end of a word r”\bain”
r”ain\b”
\B Returns the match where the specified characters are present, but NOT at the beginning (or at the end) of a word r”\Bain”
r”ain\B”
\d Returns the match where the string contains digits (numbers from 0-9) “\d”
\D Returns the match where a string DOES NOT contain digits “\D”
\s Returns the match where the string contains a white space character “\s”
\S Returns the match where the string DOES NOT contain a white space character “\S”
\w Returns the match where a string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) “\w”
\W Returns the match where the string DOES NOT contain any word characters “\W”
\Z Returns the match if the specified characters are at the end of the string. “Spain\Z”

 

#Python Sets

A set is the set of characters inside a pair of square brackets [] with a special meaning.

Set Description
[arn] Returns the match where one of the specified characters (ar, or n) are present
[a-n] Returns the match for any lower case character, alphabetically between a and n
[^arn] Returns a match for any character EXCEPT ar, and n
[0123] Returns the match where any of the specified digits (012, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns the match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns the match for any character alphabetically between a and z, lower case OR upper case
[+] In sets, +*.|()$,{} has no special meaning, so [+] means: return a match for any + character in the string

 

Example of w+ and ^ Expression

See the following characters.
  1. “^”: This expression matches a start of the string
  2. “w+“: This expression matches an alphanumeric character in a string

Here we will see the example of how we can use the w+ and ^ expression in our code. We cover re.findall function later in this tutorial, but for a while, we focus on \w+ and \^ expression.

For example, for our string “appdividend, is fun” if we execute the code with w+ and^, it will give the output “appdividend”.

See the following code.

# app.py

import re

data = "appdividend, is fun"
result = re.findall("^\w+", data)
print(result)

See the output.

Example of w+ and ^ Expression

 

Remember, if you remove the +sign from the w+, the output will change, and it will only give a first character of the first letter, i.e., [a].

Using re.match() function in Python

The match function is used to match the RE pattern to string with tge optional flags. In this method, the expression “w+” and “\W” will match the words starting with a letter ‘g’ and after that, anything which is not started with ‘g’ is not identified. If we want to check match for each element in the list or string, we run the for a loop. See the following code.

# app.py

import re

listA = ["appdividend10 giveaway",
        "appdividend10 giveup",
        "appdividend javascript"]

for element in listA:
  result = re.match("(a\w+)\W(g\w+)", element)
  if result:
    print((result.groups()))

See the following output.

Using re.match() function in Python

 

Summary

The regular expression in a programming language is the special text string used for describing a search pattern. It includes the digits and punctuation and all special characters like $#@!%, etc. An expression can include literal

  1. Text matching
  2. Repetition
  3. Branching
  4. Pattern-composition etc.

In Python, the regular expression is denoted as RE (REs, regexes or regex pattern) are embedded through re module.

  1. The “re” module included with Python primarily used for string searching and manipulation
  2. Also used frequently for webpage “Scraping” (extract the large amount of data from websites)
  3. Regular Expression Methods include the re.match(),re.search()& re.findall()
  4. Python Flags Many Python Regex Methods, and Regex functions take an optional argument called Flags
  5. This flags can modify the meaning of a given Regex pattern
  6. Many Python flags used in Regex Methods are re.M, re.I, re.S, etc.

Finally, Python RegEx Tutorial With Example | Regular Expressions in Python is over.

The post Python RegEx Tutorial With Example | Regular Expressions in Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/06/10/python-regex-tutorial-with-example-regular-expressions-in-python/feed/ 0
Python Logging Tutorial With Example | Logging in Python https://appdividend.com/2019/06/08/python-logging-tutorial-with-example-logging-in-python/ https://appdividend.com/2019/06/08/python-logging-tutorial-with-example-logging-in-python/#respond Sat, 08 Jun 2019 09:24:25 +0000 http://localhost/wordpress/?p=8199 Python Logging Tutorial With Example | Logging in Python

Python Logging Tutorial With Example | Logging in Python is today’s topic. The logging module defines functions and classes which implement the flexible event logging system for applications and libraries. The key benefit of having a logging API provided by a standard library module is that all Python modules can participate in the logging, so […]

The post Python Logging Tutorial With Example | Logging in Python appeared first on AppDividend.

]]>
Python Logging Tutorial With Example | Logging in Python

Python Logging Tutorial With Example | Logging in Python is today’s topic. The logging module defines functions and classes which implement the flexible event logging system for applications and libraries. The key benefit of having a logging API provided by a standard library module is that all Python modules can participate in the logging, so your application log can include your messages integrated with messages from third-party modules.

Python Logging Tutorial With Example

Although logging is essential, not all developers know how to use them correctly. I saw some developers insert the print statements when developing and remove those statements when it is finished.

It works when a program is a simple script, but for complex systems, you better not to use this print approach. First of all, you cannot leave only essential messages in the log, you may see the lots of garbage messages in the log, but can’t find anything fruitful. You also cannot control those print statements without modifying the code, and you may forget to remove those unused prints. And all the printed messages go into stdout, which is terrible when you have the data to output to the stdout. Of course you can print the messages to stderr, but still, it is not a good practice to use print for logging.

Logging is a handy tool in the programmer’s toolbox. It can help you develop a the flow of the program and discover scenarios that you might not even have thought of while developing an app.

Logs provide developers with the extra set of eyes that are always looking at the flow that the application is going through. They can store the information, like which user or IP accessed an app. If the error occurs, then they can provide more insights than the stack trace by telling you what the state of a program was before it arrived at the line of code where an error occurred.

By logging the useful data from the right places, you can not only debug the errors easily but also use the data to analyze a performance of an application to plan for scaling or look at the usage patterns to plan for marketing.

#The Logging Module in Python

The logging module in Python is the ready-to-use and powerful module that is designed to meet the needs of the beginners as well as the enterprise teams.

You can import the Logging module using the following line of code.

import logging

After the logging module imported, you can use something called a “logger” to log the messages that you want to see. By default, there are total five standard levelsm which are indicating the severity of events. Each has the corresponding method that can be used to log the events at that level of seriousness. The defined levels are the following:

  1. DEBUG
  2. INFO
  3. WARNING
  4. ERROR
  5. CRITICAL

The logging module provides you with the default logger that allows you to get started without needing to do many configurations.

# app.py

import logging

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

Now run the above file in the terminal, and you can see the following output.

 

Python Logging Tutorial With Example

One thing from the above output you can note that we only got the three output and not five.

The above output shows that the severity level before each message along with a root, which is the name, the logging module gives to its default logger. (Loggers are discussed in detail in the later sections.) In this format, which shows the level, name, and message separated by the colon (:), is a default output format that can be configured to include the things like timestamp, line number, and the other details.

Notice that the debug() and info() messages didn’t get logged. It is because, by default, the logging module logs the messages with the severity level of WARNING or above. You can change that by configuring a logging module to log the events of all levels if you want. You can also define your severity levels by changing configurations, but it is generally not recommended as it can confuse with logs of some third-party libraries that you might be using.

#Logging Basic Configurations

You can use the basicConfig(args) method to configure the logging.

Commonly used parameters for the basicConfig() are the following.

  • level: The root logger will be set to a specified severity level.
  • filename: This specifies the file.
  • filemode: If the filename is given, the file is opened in this mode. The default is a, which means append.
  • form: This is the format of the log message.

Now, see the following example of Python Logging.

# app.py

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('Start reading database')

# read database here
records = {'krunal': 26, 'ankit': 24}
logger.debug('Records: %s', records)
logger.info('Updating records ...')
records = {'krunal': 27, 'ankit': 25}

# update records here
logger.info('Finish updating records')

Now, run the above file and see the output.

Logging Basic Configurations

 

So, By using a level parameter, you can set what level of log messages you want to record. It can be done by passing one of the constants available in the class, and this would enable all the logging calls at or above that level to be logged.

The debug(), info(), warning(), error(), and critical() also call the basicConfig() without arguments automatically if it has not been called before. What this means that after a first time one of the above functions is called, you can no longer configure a root logger because they would have called a basicConfig() function internally.

You can use the FileHandler to write records to a file. See the following code example.

# app.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('info.log')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)

logger.info('See the info.log file')

Now, run the file and one file is created in the same directory as your app.py file called info.log and now see the output of the file. The output is following.

2019-06-07 23:02:03,617 - __main__ - INFO - See the info.log file

So, you can create log files in your file system to track the changes in your applications. Most web frameworks and CMS follow this approach so that when app will crash, they will see this kind of log file to figure out what went wrong.

#Formatting the Logging Output in Python

Format string in Python is effortless. Same as Logging module. You can pass the variable that can be represented as the string from your program as the message to your logs, and some essential elements are already a part of the LogRecord and can be easily added to an output format. If you want to log a process ID along with the level and message. See the following code example.

# app.py

import logging

logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This statement is a Warning')

See the below output.

Formatting the Logging Output in Python

 

Here is an another example where you can add the current date and time info.

import logging

logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('Krunal has logged in')

See the output.

Logging Format in Python

 

%(asctime) adds the time of the creation of the LogRecord. The format can be changed using a datefmt attribute, which uses the same formatting language as the formatting functions in the Python datetime module, such as the time.strftime().

#Logging Variable Data

The logging methods take the string as an argument, and it might seem natural to format the string with variable data in a separate line and pass it to the log method.

But this can be done directly by using a format string for the message and appending the variable data as arguments. See the following example.

# app.py

import logging

name = 'Krunal'

logging.warning('%s raised a warning', name)

See the following output.

Logging Variable Data

 

The arguments passed to a method would be included as the variable data in the message.

While you can use any formatting style you want, the f-strings introduced in Python 3.6 are an excellent way to format the strings as they can help keep the formatting short and easy to read.

# app.py

import logging

name = 'Krunal'

logging.warning(f'{name} raised an warning')

 

logging methods in Python

Classes and Functions

You can (and should) define your logger by creating an object of a Logger class, especially if your application has the multiple modules. Let’s have the look at some of the classes and functions in Python module.

The most common classes defined in the logging module are the following.

  • Logger: This is the class whose objects will be used in the application code directly to call the functions.

  • LogRecord: Loggers automatically create the LogRecord objects that have all the information related to an event being logged, like the name of a logger, the function and the line number, the message, and more.
  • Handler: Handlers send a LogRecord to the required the output destination, like the console or the file. The handler is the base for subclasses like the StreamHandler, FileHandler, SMTPHandler, HTTPHandler, and more. These subclasses send the logging outputs to the corresponding destinations, like sys.stdout or the disk file.
  • Formatter: This is where you specify the format of the output by specifying the string format that the lists out the attributes that the output should contain.

We mostly deal with the objects of a Logger class, which are instantiated using a module-level function logging.getLogger(). Multiple calls to getLogger() with a same name will return a reference to the same Logger object, which saves us from passing the logger objects to every part where it’s needed.

See the following example.

# app.py

import logging

logger = logging.getLogger('demo logger')
logger.error('This is an error')

See the output.

Logging in Python example

 

So, in this tutorial, we have discussed The logging module in Python, Logging basic configurations, classes, and functions, logging variable and data, and formatting logging output.

Finally, Python Logging Tutorial With Example | Logging in Python is over.

The post Python Logging Tutorial With Example | Logging in Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/06/08/python-logging-tutorial-with-example-logging-in-python/feed/ 0
Python Collections Tutorial With Example | Python’s Collections Module https://appdividend.com/2019/05/27/python-collections-tutorial-with-example-pythons-collections-module/ https://appdividend.com/2019/05/27/python-collections-tutorial-with-example-pythons-collections-module/#respond Mon, 27 May 2019 12:11:24 +0000 http://localhost/wordpress/?p=7616 Python Collections Tutorial With Example | Python's Collections Module

Python Collections Tutorial With Example | Python’s Collections Module is today’s topic. The collections module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers like a dictionary, list, set, and tuple. In addition to the particular container classes, the collections module provides abstract base classes that can be used to test whether the class provides a specific […]

The post Python Collections Tutorial With Example | Python’s Collections Module appeared first on AppDividend.

]]>
Python Collections Tutorial With Example | Python's Collections Module

Python Collections Tutorial With Example | Python’s Collections Module is today’s topic. The collections module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers like a dictionary, listset, and tuple. In addition to the particular container classes, the collections module provides abstract base classes that can be used to test whether the class provides a specific interface, for example, whether it is hashable or a mapping.

Python Collections Tutorial With Example

Python collection is similar to a basket that you can add and remove items from. In some cases, they are the same types of elements, and in others, they are different types of items. It’s the storage construct that allows us to collect the items. Python collections module was introduced to improve the functionalities of built-in collection containers. Collections module was first introduced in 2.4 release of Python.

The collection will survive in memory. You don’t need to build the collection or create any scaffolding. All of that is provided for free. Just create a collection instance and start adding your items. When you’re ready, you can pull the items out by name or by index (position within the collection).

Collections Module in Python

See the following Python Collections.

  1. Counter
  2. defaultdict
  3. OrderedDict
  4. deque
  5. namedtuple()

Counter

The Counter collections allow us to keep the count of all the items which are inserted into a collection with the keys. The Counter is the dictionary subclass for counting the hashable objects. It is the unordered collection where items are stored as dictionary keys, and their counts are stored as the dictionary values. Counts collections are allowed to be any integer value, including zero or negative counts. The Counter class is similar to bags or multisets in the other languages.

See the following code example.

# app.py

from collections import Counter

aladdinChars = [
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

count = Counter(name for name, actual in aladdinChars)
print(count)

See the following output.

Python Collections Tutorial With Example

 

This way, we can count the number of times the key appeared in the list.

Items are counted from the iterable or initialized from another mapping (or counter).

# app.py

from collections import Counter
c = Counter(apple=4, samsung=8)
print(c)

See the output.

Python Counter Collections

 

Default Dict

The default dict can contain the duplicate keys. The advantage of using the default dictionary is that we can collect elements which belong to the same key. It returns a new dictionary-like object.

The defaultdict is the subclass of the built-in dict class.

Defaultdict overrides one method and adds one writable instance.

The remaining functionality is the same as for a dict class. See the following code example.

# app.py

from collections import defaultdict

aladdinChars = [
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

dict_chars = defaultdict(list)

for key, value in aladdinChars:
    dict_chars[key].append(value)

print(list(dict_chars.items()))

See the below output.

Default Dict Tutorial

 

Now, let’s repeat the Jasmine value one more time and see the output.

# app.py

from collections import defaultdict

aladdinChars = [
    ('Jasmine', 30),
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

dict_chars = defaultdict(list)

for key, value in aladdinChars:
    dict_chars[key].append(value)

print(list(dict_chars.items()))

See the output below.

Default Dict

 

OrderedDict

With an OrderedDict, an order of insertion is maintained when the key and values are inserted into a dictionary. If we try to add a key again, this will overwrite the previous value for that key. Here is a sample program to demonstrate the usage of an OrderDict.

# app.py

from collections import OrderedDict

aladdinChars = OrderedDict([
    ('Jasmine', 30),
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
])

for key, value in aladdinChars.items():
    print(key, value)

See the output below.

OrderedDict Tutorial

 

In the above example, you can see that Jasmin value is repeated one more time, still, in the output, it appears only one time. That means, it will remove the duplicate values and also you can see that it has given us the values in order. The output order was the same as the order of insertion.

Deque

A Deque is a double-ended queue which allows us to add and remove the items from both the ends. It enhances the capabilities of a stack or a queue. Deques are the generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends, and pop from either side of the deque with approximately the same O(1) performance in the either direction.

See the following code example of Deque in Python.

# app.py

from collections import deque

webname = deque('AppDividend')
print('Deque       :', webname)
print('Queue Length:', len(webname))
print('Left part   :', webname[0])
print('Right part  :', webname[-1])

webname.remove('A')
print('remove(After removing A):', webname)

See the following output.

Deque Tutorial

 

So, the dequeuing of the items were done automatically. We can also add items in the Deque on a specific end.

namedtuple

Python Tuples are the immutable lists. What this means that the value cannot be given to the key which already exists in a tuple. We can convert that Tuple to the Named tuple by assigning the name to all values present in that tuple. It will give a lot more context to the data present as well. See the following code.

# app.py

from collections import namedtuple

Person = namedtuple('Employee', 'name age gender')
data = Person(name='Krunal', age=26, gender='M')
print(data)
print('Name of Employee: {0}'.format(data.name))

See the output below.

namedtuple

 

So, that is how we can access the properties of a named tuple with a name we provide. Also, remember that a key name cannot be any Python keywords.

Finally, Python Collections Tutorial With Example | Python’s Collections Module article is over.

The post Python Collections Tutorial With Example | Python’s Collections Module appeared first on AppDividend.

]]>
https://appdividend.com/2019/05/27/python-collections-tutorial-with-example-pythons-collections-module/feed/ 0
How To Remove Character From String In Python Tutorial With Example https://appdividend.com/2019/05/25/how-to-remove-character-from-string-in-python-tutorial-with-example/ https://appdividend.com/2019/05/25/how-to-remove-character-from-string-in-python-tutorial-with-example/#respond Sat, 25 May 2019 11:48:33 +0000 http://localhost/wordpress/?p=7516 How To Remove Character From String In Python Tutorial With Example

How To Remove Character From String In Python Tutorial With Example is today’s topic. In Python, the string object is immutable and hence sometimes poses visible restrictions while coding the constructs that are required in day-day programming. This article presents the solution of removing the character from the string. We will see different methods and […]

The post How To Remove Character From String In Python Tutorial With Example appeared first on AppDividend.

]]>
How To Remove Character From String In Python Tutorial With Example

How To Remove Character From String In Python Tutorial With Example is today’s topic. In Python, the string object is immutable and hence sometimes poses visible restrictions while coding the constructs that are required in day-day programming.

This article presents the solution of removing the character from the string. We will see different methods and approaches.

How To Remove Character From String In Python

We have two ways to remove the character in Python.

  1. Using string replace() function.
  2. Using string translate() function.

Using string replace()

We can use the string replace() method to replace the character with a new character. If we provide the empty string as the second argument, then a character will get removed from a string.

One thing to note that the string is immutable in Python so that the replace() function will return the new string and the original string will remain unchanged.

See the following example.

# app.py

strA = "Game of Thrones"
print(strA.replace('Game', ''))

See the output.

Using string replace()

 

In the above output, we have removed the Games from the string. We have removed with an empty string, and now the Games word is removed.

We can replace the word with another word. See the following code.

# app.py

strA = "Game of Thrones"
print(strA.replace('Game', 'Memes'))

See the output.

How To Remove Character From String In Python

 

Now, remove one character from the string. See the following code.

# app.py

strA = "Game of Thrones"
print(strA.replace('G', ''))

See the output.

Ways to remove i’th character from string in Pytho

 

Hence, the string.replace() function can be used for performing the task of removal as we can replace the particular index with empty char, and hence solve the issue.

Using string translate()

Python string translate() function replace each character in a string using the given translation table.

We have to specify a Unicode code point for a character and ‘None’ as the replacement to remove it froma result string. We can use the ord() function to get the Unicode code point of the character.

See the following code example.

Using string translate()

 

If you want to replace the multiple characters, that can be done quickly using an iterator. Let’s see how to remove characters ‘a,’ ‘b’ and ‘c’ from a string. See the below code.

# app.py

strA = "Game of Thrones"
print(strA.translate({ord(i): None for i in 'Game'}))

See the below output.

Using string translate() example

 

You can see in the output that Game word is removed, but also any occurrences of G, a, m, and e character is also removed from the entire string so if the above character is repeated multiple times in the string than also it will remove all the repeated characters.

Removing Spaces from a String

If you want to remove the spaces from the beginning and ending of the string, then you can use the Python String strip standard method.

You can also use the following method. See the below code.

# app.py

strA = " G a m e o f T h r o n e s "
print(strA.replace(' ', ''))
print(strA.translate({ord(i): None for i in ' '}))

See the output below.

Removing Spaces from a String

 

Remove specified number of times

We can also pass a third parameter in replace() function to specify the number of times replacement should be performed. See the following code.

# app.py

strA = "Game of Thrones"
print(strA.replace('e', 'E', 2))

See the output.

Remove specified number of times

 

Python Remove newline from String

See the following code example where we remove /n character.

# app.py

strA = "Game \nof \nThrones"
print(strA.replace('\n', ''))
print(strA.translate({ord('\n'): None}))

See the output.

Python Remove newline from String

 

Using slice + concatenation

One can use string slice and slice the string before the pos i, and slice after the pos i. Then using string concatenation of both, an i’th character can appear to be deleted from the string. See the below code example.

# app.py

strA = "Game of Thrones"
 
print ("The original string is : " + strA) 

# using slice + concatenation 
strO = strA[:2] +  strA[3:] 
  
# Printing string after removal   
# removes ele. at 3rd index 
print ("The string after removal of i'th character : " + strO)

In the above code, we have removed the third index and then concat the remaining string. See the following output.

Using slice + concatenation

 

Finally, How To Remove Character From String In Python Tutorial With Example is over.

The post How To Remove Character From String In Python Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/05/25/how-to-remove-character-from-string-in-python-tutorial-with-example/feed/ 0