Python – AppDividend https://appdividend.com Latest Code Tutorials Tue, 19 Nov 2019 09:52:25 -0500 en-US hourly 1 https://wordpress.org/?v=5.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Python – AppDividend https://appdividend.com 32 32 Python String isalpha() Method Example https://appdividend.com/2019/11/19/python-string-isalpha-method-example/ https://appdividend.com/2019/11/19/python-string-isalpha-method-example/#respond Tue, 19 Nov 2019 09:48:53 +0000 http://localhost/wordpress/?p=12532 Python String isalpha() Method Example

Python String isalpha() method in python is used to check whether the given string consists of only alphabets. In other words, we can say that it is a method of handling strings. Python isalpha() returns True if every character of the string is an alphabet and returns False otherwise. Python String isalpha() If you want […]

The post Python String isalpha() Method Example appeared first on AppDividend.

]]>
Python String isalpha() Method Example

Python String isalpha() method in python is used to check whether the given string consists of only alphabets. In other words, we can say that it is a method of handling strings. Python isalpha() returns True if every character of the string is an alphabet and returns False otherwise.

Python String isalpha()

If you want to check if the string contains only the alphabet, then Python isalpha() function solves your problem. See the following syntax.

Syntax

string.isalpha()

It doesn’t take any parameters. There will error shown if we try to pass any parameter to the method.

The isalpha() function returns true if the string consists only of alphabets. (Both uppercase and lowercase)

Python string isalpha() function returns False if the string doesn’t contain alphabets or contains characters other than alphabets like numerical or special characters. When it identifies a space, then also it returns False.

Algorithm

1. Initialize the new string and variable counter to 0.
2. Traverse the given string character by character up to its length, check if the character is an alphabet.
3. If it is an alphabet, increment the counter by 1 and add it to the new string, else traverse to the next character.
4. Print a value of the counter and the new string.

Example programs on isalpha() method

Write a program to show the mechanism of isalpha()
# app.py

string = "HelloBoy"
string2 = "Hello Boy"
print("This string will return true as it contains only alphabets:")
print("String=", string)
print(string.isalpha())
print("This string will return false as it contains alphabets and one space:")
print("String=", string2)
print(string2.isalpha())

Output

➜  pyt python3 app.py
This string will return true as it contains only alphabets:
String= HelloBoy
True
This string will return false as it contains alphabets and one space:
String= Hello Boy
False
➜  pyt
Write a program to count the alphabets of the string.
# app.py

string = "Hello World"
count = 0
count1 = 0
for i in string:
    if(i.isalpha()) == True:
        count = count+1
for i in string:
    count1 = count1+1
print("String: ", string)
print("Length of the string including space: ", count1)
print("Length of the string just by counting alphabets: ", count)

Output

➜  pyt clear
➜  pyt python3 app.py
String:  Hello World
Length of the string including space:  11
Length of the string just by counting alphabets:  10
➜  pyt

Errors and Exceptions

  1. It contains no arguments; therefore, an error occurs if a parameter is passed.
  2. Both uppercase and lowercase alphabets return “True”.
  3. Space is not considered to be the alphabet; therefore, it returns “False”.

Finally, Python String isalpha() Method Example is over.

Related Posts

Python string isalnum()

Python string encode()

Python string isdecimal()

Python string isdigit()

Python string to list

The post Python String isalpha() Method Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/19/python-string-isalpha-method-example/feed/ 0
Python String isalnum() Method Example https://appdividend.com/2019/11/19/python-string-isalnum-method-example/ https://appdividend.com/2019/11/19/python-string-isalnum-method-example/#respond Tue, 19 Nov 2019 09:13:05 +0000 http://localhost/wordpress/?p=12521 Python String isalnum() Method Example

Python string isalnum() method in python is used to check whether the given string consists of only alphabets and numbers. In other words, we can say that it checks if the characters present in the string are alphanumeric or not. Isalnum() method returns True if a string is alphanumeric otherwise it returns False. Python isalum() […]

The post Python String isalnum() Method Example appeared first on AppDividend.

]]>
Python String isalnum() Method Example

Python string isalnum() method in python is used to check whether the given string consists of only alphabets and numbers. In other words, we can say that it checks if the characters present in the string are alphanumeric or not. Isalnum() method returns True if a string is alphanumeric otherwise it returns False.

Python isalum() is the perfect function to check if the string contains the alphanumeric characters or not. It solves the problem.

Python String isalnum()

Python isalnum() function in Python language checks whether all the characters in a given string is alphanumeric or not.

Syntax

string.isalnum()

Python string isalnum() doesn’t take any parameters.

Python isalnum() returns:

  1. True if all the characters in the string are alphanumeric.
  2. False if at least one character is not alphanumeric.

Write the program to show a mechanism of isalnum().

See the following code.

# app.py

string = "HelloWorld123"
string2 = "Hello!-World!-123..."
print("Output for the string which is alphanumeric:")
print(string.isalnum())
print("Output for the string which is not alphanumeric:")
print(string2.isalnum())

Output

➜  pyt python3 app.py
Output for the string which is alphanumeric:
True
Output for the string which is not alphanumeric:
False
➜  pyt

Write a program to check multiple strings if they are alphanumeric.

See the following code.

# app.py

string = "This world is a strange place!"
string2 = "People over here are not awesome!"

if(string.isalnum() == True and string2.isalnum() == True):
    print("This world is a strange place to live and people over here are not awesome!")
else:
    print("This world is not a strange place to live and people over here are awesome!")

Output

➜  pyt python3 app.py
This world is not a strange place to live and people over here are awesome!
➜  pyt

These (space)!#%&? characters are not alphanumeric.

See the following code example.

# app.py

string = "Krunal#$110470116021"

if(string.isalnum() == True):
    print("The string is alphanumeric!")
else:
    print("The string is not alphanumeric")

Output

➜  pyt python3 app.py
The string is not alphanumeric
➜  pyt

Printing all Alphanumeric characters in Python

We can use the Unicode module to check if the character is alphanumeric or not. Here is the program to print all the alphanumeric Unicode characters.

See the following code.

# app.py

import unicodedata

count = 0
for cdpt in range(2 ** 16):
    ch = chr(cdpt)
    if ch.isalnum():
        print(u'{:04x}: {} ({})'.format(
            cdpt, ch, unicodedata.name(ch, 'UNNAMED')))
        count = count + 1
print(f'Total Number of Alphanumeric Unicode Characters = {count}')

Output

ffbd: ᄑ (HALFWIDTH HANGUL LETTER PHIEUPH)
ffbe: ᄒ (HALFWIDTH HANGUL LETTER HIEUH)
ffc2: ᅡ (HALFWIDTH HANGUL LETTER A)
ffc3: ᅢ (HALFWIDTH HANGUL LETTER AE)
ffc4: ᅣ (HALFWIDTH HANGUL LETTER YA)
ffc5: ᅤ (HALFWIDTH HANGUL LETTER YAE)
ffc6: ᅥ (HALFWIDTH HANGUL LETTER EO)
ffc7: ᅦ (HALFWIDTH HANGUL LETTER E)
ffca: ᅧ (HALFWIDTH HANGUL LETTER YEO)
ffcb: ᅨ (HALFWIDTH HANGUL LETTER YE)
ffcc: ᅩ (HALFWIDTH HANGUL LETTER O)
ffcd: ᅪ (HALFWIDTH HANGUL LETTER WA)
ffce: ᅫ (HALFWIDTH HANGUL LETTER WAE)
ffcf: ᅬ (HALFWIDTH HANGUL LETTER OE)
ffd2: ᅭ (HALFWIDTH HANGUL LETTER YO)
ffd3: ᅮ (HALFWIDTH HANGUL LETTER U)
ffd4: ᅯ (HALFWIDTH HANGUL LETTER WEO)
ffd5: ᅰ (HALFWIDTH HANGUL LETTER WE)
ffd6: ᅱ (HALFWIDTH HANGUL LETTER WI)
ffd7: ᅲ (HALFWIDTH HANGUL LETTER YU)
ffda: ᅳ (HALFWIDTH HANGUL LETTER EU)
ffdb: ᅴ (HALFWIDTH HANGUL LETTER YI)
ffdc: ᅵ (HALFWIDTH HANGUL LETTER I)
Total Number of Alphanumeric Unicode Characters = 49473
➜  pyt

Related Posts

Python string isdigit()

Python string encode()

Python string isdecimal()

Python dictionary to string

Python string to list

The post Python String isalnum() Method Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/19/python-string-isalnum-method-example/feed/ 0
Python String encode() Method Example https://appdividend.com/2019/11/19/python-string-encode-method-example/ https://appdividend.com/2019/11/19/python-string-encode-method-example/#respond Tue, 19 Nov 2019 07:08:00 +0000 http://localhost/wordpress/?p=12511 Python String encode() Method Example

Before understanding, python string encode() method, we need to understand what is encoding. So to start within python, the strings are stored in the form of Unicode, and for increasing the efficiency of storage of the strings, these unicodes are converted in a set of bytes. This complete process is known as encoding. With the […]

The post Python String encode() Method Example appeared first on AppDividend.

]]>
Python String encode() Method Example

Before understanding, python string encode() method, we need to understand what is encoding. So to start within python, the strings are stored in the form of Unicode, and for increasing the efficiency of storage of the strings, these unicodes are converted in a set of bytes. This complete process is known as encoding.

With the help of strings encode() method, we can convert unicodes of that string to any encodings that are supported by python.

Encoding is also essential as it holds the key in case of security. So to store different data in databases, it has become a need to use an encoding. For example, passwords are strings and to encode that in python, we use the encode() function. 

There are different encoding schemes defined in the language such as utf-8, ascii, ibm039, etc.

Python String encode()

The encode() method encodes the string, using a specified encoding. If no encoding is specified, then UTF-8 will be used.

Syntax

string_var.encode(encoding, errors)

See the following parameters.

Encoding: Type of encoding in which the string is supposed to be encoded.

Errors: Response given when the encoding fails, there are about six encoding error responses.

It returns the encoded string.

In case of failure, it raises the UnicodeDecodeError exception.

Example programs on string encode() method

Write a program to show the mechanism of string encode()

# app.py

str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode()
print(str2)

Output

➜  pyt python3 app.py
b'Hello and welcome to the world of pyth\xc3\xb6n!'
➜  pyt
Write a program to encode a string bypassing both the parameters and show the output.
# app.py

str1 = "Hello pythön!!"
print(str1.encode("ascii", "replace"))
Output
➜  pyt python3 app.py
b'Hello pyth?n!!'
➜  pyt

In today’s world, security holds the key to many of the applications.

Thus the need for secure storage of passwords in the database is required, and hence there is to save encoded versions of strings.

We can achieve this, python in its language has defined “encode()” that encodes strings with the specified encoding scheme. There are several encoding schemes defined in the language.

Conclusion

Python encode() method encodes the string according to the provided encoding standard. By default, Python strings are in Unicode form but can be encoded to other standards also.

Finally, Python String encode() Method Example is over.

Related Posts

Python string isdecimal()

Python string isdigit()

Python string to list

Python string capitalize()

Python string casefold()

The post Python String encode() Method Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/19/python-string-encode-method-example/feed/ 0
Python String isdecimal() Method Example https://appdividend.com/2019/11/19/python-string-isdecimal-method-example/ https://appdividend.com/2019/11/19/python-string-isdecimal-method-example/#respond Tue, 19 Nov 2019 06:28:20 +0000 http://localhost/wordpress/?p=12499 Python String isdecimal() Method Example

Python string isdecimal() method is used to check whether the given string consists of only decimals. In other words, we can say that it checks if the characters present in the string are decimal or not. Python isdecimal() method returns true if the string has its all character as a decimal and false otherwise. So, […]

The post Python String isdecimal() Method Example appeared first on AppDividend.

]]>
Python String isdecimal() Method Example

Python string isdecimal() method is used to check whether the given string consists of only decimals. In other words, we can say that it checks if the characters present in the string are decimal or not. Python isdecimal() method returns true if the string has its all character as a decimal and false otherwise.

So, if you want to check the decimals in the string, then the Python isdecimal() method is beneficial.

Python String isdecimal()

It is a function in Python that returns True if all characters in a string are decimal. If all characters are not decimal, then it returns False.

Syntax

string.isdecimal()

The isdecimal() function doesn’t take any parameters. There will error shown if we try to pass any parameter to the method.

It returns true if the string consists only of decimals.

It returns False if the string doesn’t contain decimals or contains characters other than decimals like numerical or special characters. When it identifies a space, then also it returns False.

Programs on isdecimal() method

Write a program to demonstrate the use of the isdecimal() method.

# app.py

string = "123456"
print(string.isdecimal())

Output

➜  pyt python3 app.py
True
➜  pyt

Write a program to check multiple strings using the isdecimal() method.

# app.py

string = "123456"
string2 = "123 456"
print(string.isdecimal())
print(string2.isdecimal())

Output

➜  pyt python3 app.py
True
False
➜  pyt

The superscript and subscripts are considered digit characters but not decimals. If the string contains these characters (usually written using Unicode), isdecimal() returns False.

See the following code.

# app.py

string = "123456"
string2 = "19k21k"
string3 = "11m 21k"
print(string.isdecimal())
print(string2.isdecimal())
print(string3.isdecimal())

Output

➜  pyt python3 app.py
True
False
False
➜  pyt

Similarly, roman numerals, currency numerators, and fractions are considered numeric numbers (usually written using Unicode) but not decimals. The isdecimal() also returns False.

There are two methods isdigit() and isnumeric() that check whether the string contains digit characters and numeric characters, respectively.

String Containing digits and Numeric Characters

See the following code.

# app.py

string = '\u00B48155'
string2 = '\u00BD'
print(string.isdecimal())
print(string2.isdecimal())

Output

➜  pyt python3 app.py
False
False
➜  pyt

Finally,  Python String isdecimal() Method Example is over.

Related Posts

Python String capitalize()

Python String casefold()

Python String expandtabs()

Python String center()

Python String endswith()

The post Python String isdecimal() Method Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/19/python-string-isdecimal-method-example/feed/ 0
Python String isdigit() Function Example https://appdividend.com/2019/11/18/python-string-isdigit-function-example/ https://appdividend.com/2019/11/18/python-string-isdigit-function-example/#respond Mon, 18 Nov 2019 11:40:24 +0000 http://localhost/wordpress/?p=12464 Python String isdigit() Function Example

Python string isdigit() method in python is used to check whether the given string consists of only digits. In other words, we can say that it checks if the characters present in the string are digits or not. Python isdigit() method returns true if the string has its all character as digits and false otherwise. […]

The post Python String isdigit() Function Example appeared first on AppDividend.

]]>
Python String isdigit() Function Example

Python string isdigit() method in python is used to check whether the given string consists of only digits. In other words, we can say that it checks if the characters present in the string are digits or not. Python isdigit() method returns true if the string has its all character as digits and false otherwise.

If you want to put the validation, then this function might be useful to you.

Exponents, like ², are also considered to be a digit.

Python String isdigit()

The isdigit() function is used to check if the argument contains digits such as 0123456789

Syntax

string.isdigit()

The function doesn’t take any parameters. There will error shown if we try to pass any parameter to the method.

It returns true if the string consists of only digits.

It returns false if the string doesn’t contain digits or contains characters other than digits like numerical or special characters. When it identifies a space, then also it returns false.

We can use the ascii values of characters and print the digits using isdigit().

See the following example.

string_variable = “1234”
print(string_variable.isdigit())

Output

True

Write a program to show the mechanism of the isdigit() method.

# app.py

string = "12345"
print("It will print true as the string contains only digits:")
print(string.isdigit())

Output

It will print true as the string contains only digits:
True

Write a program to traverse the string using ascii value and print the digits.

y = ""
for var in range(0, 60, 1):
    x = chr(var)
    if(x.isdigit() == True):
        y += x

print("String:", y)

Output

String: 0123456789

Python isdigit float

Python str.isdigit() will only return True if all characters in the string are digits. The ‘.’ is punctuation, not a digit. Formally, the digit is a character that has the property value Numeric_Type = Digit or Numeric_Type = Decimal.

(For Python 2, for str objects only the ASCII digits (0 through to 9) are considered, but for Unicode objects, the same definition applies).

Python isdigit() function with negative arguments

See the following code.

# app.py

data = '-21'

if data.isdigit() is True:
    print('We can use isdigit() function on negative number')
else:
    print('We can\'t use the isdigit() function')

Output

We can't use the isdigit() function

I can type in numbers fine, and this would filter out alpha/alphanumeric strings.

When I put a negative number such as -1, ‘.isdigit’ counts ‘-‘ sign as a string value, and it rejects it. So, it would go to (else).

When I try ‘s1’ and ‘s’ for example, it will go to (else).

Errors And Exceptions

  1. It does not take any arguments; therefore, the isdigit() function returns an error if the parameter is passed.
  2. Superscript and subscripts are considered the digit characters along with decimal characters; therefore, Python isdigit() function returns “True”.
  3. The roman numerals, currency numerators, and fractions are not considered to be digits. Therefore, Python isdigit() function returns “False”.

Algorithm

  1. Initialize the new string and a variable count=0.
  2. It traverses every character using ASCII value, check if the character is the digit or not.
  3. If it is the digit, increment the count by 1 and add it to the new string, else traverse to the next character.
  4. Print the value of a counter and a new string.

Application of isdigit()

Using ASCII values of characters, count and print all the digits using the isdigit() function.

Finally, Python String isdigit() Function Example is over.

Related Posts

How to convert Python string to list

Python string capitalize()

Python string casefold()

Python string expandtabs()

Python string center()

The post Python String isdigit() Function Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/18/python-string-isdigit-function-example/feed/ 0
How To Find Element In List In Python https://appdividend.com/2019/11/16/how-to-find-element-in-list-in-python/ https://appdividend.com/2019/11/16/how-to-find-element-in-list-in-python/#respond Sat, 16 Nov 2019 09:38:50 +0000 http://localhost/wordpress/?p=12424 How To Find Element In List In Python

In this tutorial, we will see how to search an element in list in Python. The list is an essential container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. There are so many ways that you can find an element […]

The post How To Find Element In List In Python appeared first on AppDividend.

]]>
How To Find Element In List In Python

In this tutorial, we will see how to search an element in list in Python. The list is an essential container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming.

There are so many ways that you can find an element in the list, some of which are the following.

  1. Find an element in the list by index in Python.
  2. Python Linear search on the list. 

Find Element In List By Index In Python

Python list index() method searches an element in the list and returns its index.

Python index() method finds the given element in the list and returns its position. If the same element is present more than once, the method returns the index of the first occurrence of the element.

The index in Python starts from 0, not 1.

So through an index, we can find the position of an element in the list.

See the following code example.

# app.py

streaming = ['netflix', 'hulu', 'disney+', 'appletv+']

index = streaming.index('disney+')
print('The index of disney+ is:', index)

Output

➜  pyt python3 app.py
The index of disney+ is: 2
➜  pyt

The index() method takes a single argument, which is the element, and it returns its position in the list.

Python search on the list

It is the straightforward approach is to do a linear search, for example,

  1. Start from the leftmost item of the list and one by one compare x with each item of the list.
  2. If x matches with an item, return True.
  3. If x doesn’t match with any of the items, return False.

See the following code.

# app.py

def search(list, platform):
    for i in range(len(list)):
        if list[i] == platform:
            return True
    return False


streaming = ['netflix', 'hulu', 'disney+', 'appletv+']
platform = 'netflix'

if search(streaming, platform):
    print("Platform is found")
else:
    print("Platform does not found")

In the above code, we have first created a user-defined function called search that accepts two arguments.

The first argument is our list in which we need to find the item, and the second parameter is the platform, which is the string we need to search in the list.

So, we are looping through a list and compare each element of the list to the platform argument.

If both are matched, then the element is found; otherwise, it is not.

Output

➜  pyt python3 app.py
Platform is found
➜  pyt

Check if the item exists in list using “in” operator

How to check if the element exists in the list using Python in operator.

See the syntax of Python in operator.

element in list

It will return True if element exists in list else return False.

See the following code.

# app.py

streaming = ['netflix', 'hulu', 'disney+', 'appletv+']
platform = 'hulu'
if platform in streaming:
  print('Hulu is in the streaming service business')
else:
  print('It does not include')

Output

➜  pyt python3 app.py
Hulu is in the streaming service business
➜  pyt

Filtering a collection in Python

That is, finding all elements in a sequence that meet a specific condition. You can use list the comprehension or generator expressions for that.

See the following code example.

# app.py

streaming = ['netflix', 'hulu', 'disney+', 'appletv+']
platform = 'hulu'
result = any(len(elem) == 8 for elem in streaming)

if result:
    print("Yes, string with length 8 is found")
else:
    print('Not found')

In the above code, we are searching for an element whose string length is 8. If found, then it will print “Yes, string with length 8 is found” otherwise not found.

Output

➜  pyt python3 app.py
Yes, string with length 8 is found
➜  pyt

Finally, we have seen the ways to find element in list In Python.

Related Posts

How To Access Characters In String By Index In Python

How To Convert Python List To JSON

How To Convert Python Dictionary To String

How To Convert Python List To Dictionary

How To Convert Python String To List And List To String

The post How To Find Element In List In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/16/how-to-find-element-in-list-in-python/feed/ 0
How To Access Characters In String By Index In Python https://appdividend.com/2019/11/16/how-to-access-characters-in-string-by-index-in-python/ https://appdividend.com/2019/11/16/how-to-access-characters-in-string-by-index-in-python/#respond Sat, 16 Nov 2019 05:56:16 +0000 http://localhost/wordpress/?p=12409 How To Access Characters In String By Index In Python

Python Strings are the arrays of bytes representing Unicode characters. However, Python does not have the character data type, and a single character is simply a string with a length of 1. In this tutorial, we will see how to access characters in String By Index In Python. Python provides a rich set of operators, functions, […]

The post How To Access Characters In String By Index In Python appeared first on AppDividend.

]]>
How To Access Characters In String By Index In Python

Python Strings are the arrays of bytes representing Unicode characters. However, Python does not have the character data type, and a single character is simply a string with a length of 1. In this tutorial, we will see how to access characters in String By Index In Python. Python provides a rich set of operators, functions, and methods for working with strings.

String Indexing in Python

Often in programming languages, individual elements in an ordered set of data can be accessed directly using the numeric index or key value. This process is referred to as indexing.

In Python, the strings are ordered sequences of character data, and thus can be indexed in this way.

Individual characters in the string can be accessed by specifying the string name followed by a number in square brackets ([]).

Access Characters In String By Index

String indexing is zero-based in Python: the first character in the string has index 0, the next has index 1, and so on.

The index of the last character will be the length of the string – 1.

See the following example.

# app.py

str = 'Millie Bobby Brown'
print(str[7])

In Python, the indexing of strings starts from 0 till n-1, where n is the size of the string. So characters in a string of size n can be accessed from 0 to n-1.

In the above code, we are accessing character by index.

Index starts from 0, so we will go for a 7th character, which is B.

Output

➜  pyt python3 app.py
B
➜  pyt

We can access the individual characters using an index that starts from 0.

IndexError: string index out of range

If we try to attempt an index beyond the end of the string then it results in error.

See the following code.

# app.py

str = 'Millie'
print(str[7])

Output

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(str[7])
IndexError: string index out of range
➜  pyt

So, we got an error: IndexError: string index out of range.

TypeError: string indices must be integers

Only Integers are allowed to be passed as the index, float, or other types will cause a TypeError.

See the following code.

# app.py

str = 'Emma Watson'
print(str[1.5])

Output

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(str[1.5])
TypeError: string indices must be integers
➜  pyt

We have passed the float value as an index; that is why we got the TypeError: string indices must be integers.

Accessing string characters by negative index

String indices can also be specified with the negative numbers, in which case the indexing occurs from the end of the string backward:

  1. string[-1] refers to the last character,
  2. string[-2] the second-to-last character, and so on.
  3. If string size is n, then string[-n] will return the first character of the string.

See the following code.

# app.py

str = 'Emma Watson'
print(str[-6])
print(str[-5])
print(str[-len(str)])

Output

➜  pyt python3 app.py
W
a
E
➜  pyt

Attempting to index with the negative numbers beyond the start of the string results in error.

For any non-empty string str, str[len(s)-1] and str[-1] both return the last character. There isn’t any index that makes sense for the empty string.

Modifying characters in a string using []

Let’s try to modify the string by assigning specific characters to a particular position.

# app.py

str = 'Emma Watson is Hermione'
str[6] = 'K'

Output

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

We will get the TypeError: ‘str’ object does not support item assignment.

String Slicing in Python

Python also allows a form of indexing syntax that extracts substrings from a string, known as string slicing.

If str is a string, an expression of the form str[x:y] returns the portion of s starting with position x, and up to but not including position y.

Let’s say we want to extract Watson from Emma Watson string using slice, and then we can write the following code to achieve that output.

# app.py

str = 'Emma Watson is Hermione'
print(str[5:11])

Output

➜  pyt python3 app.py
Watson
➜  pyt

Again, the second index specifies the first character that is not included in the result. That may seem slightly unintuitive, but it produces this result, which makes sense: the expression str[x:y] will return a substring that is y – x characters in length, in this case, 11 – 5 = 6. So, Watson is 6 characters word.

String indices are zero-based. The first character in a string has an index 0. This applies to both standard indexing and slicing.

Conclusion

Access characters in String are basic operations in any programming language, and Python makes it very easy providing indexing and slicing.

We can access characters by providing a positive and negative index.

Finally, How To Access Characters In String By Index In Python Tutorial Example is over.

Related Posts

Python String len()

How to remove a character from String

How to reverse string in Python

How to convert Python string to list

How to convert Python string to int

The post How To Access Characters In String By Index In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/16/how-to-access-characters-in-string-by-index-in-python/feed/ 0
How To Python Dictionary To DataFrame Example https://appdividend.com/2019/11/15/how-to-python-dictionary-to-dataframe-example/ https://appdividend.com/2019/11/15/how-to-python-dictionary-to-dataframe-example/#respond Fri, 15 Nov 2019 11:49:06 +0000 http://localhost/wordpress/?p=12395 How To Python Dictionary To DataFrame Example

In this tutorial, we will see How To Python Dictionary to Dataframe Example. Pandas DataFrame is one of these structures which helps us do the mathematical computation very easy. The Data frame is the two-dimensional data structure; for example, the data is aligned in the tabular fashion in rows and columns. Pandas library is the popular […]

The post How To Python Dictionary To DataFrame Example appeared first on AppDividend.

]]>
How To Python Dictionary To DataFrame Example

In this tutorial, we will see How To Python Dictionary to Dataframe Example. Pandas DataFrame is one of these structures which helps us do the mathematical computation very easy. The Data frame is the two-dimensional data structure; for example, the data is aligned in the tabular fashion in rows and columns.

Pandas library is the popular Python package for data science and machine learning, and with good reason: it offers dominant, expressive and flexible data structures that make the data manipulation and analysis effortless, among many other things. 

Python Dictionary To Dataframe

Python dictionary is the collection that is unordered, changeable, and indexed.

Dictionaries are written with curly braces, and they have keys and values.

The Python dictionary is the unordered collection of items.

DataFrame is a two-dimensional size-mutable, potentially composite tabular data structure with labeled axes (rows and columns).

DataFrame constructor accepts the data object that can be ndarray, dictionary, etc.

Pandas DataFrame can contain the following data type of data.

  1. The Pandas Series: a one-dimensional labeled array capable of holding any data type with axis labels or index. An example of a Series object is one column from a DataFrame.
  2. The NumPy ndarray, which can be a record or structure.
  3. The two-dimensional ndarray using NumPy.
  4. Dictionaries of one-dimensional ndarray’s, lists, dictionaries, or Series.

See the following syntax of Pandas DataFrame.

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

If we are passing the dictionary in data, then it should contain the list like objects in value field like Series, arrays or lists, etc.

Let’s initialize the following dictionary.

# app.py

StrangerThings = {
    'name': ['Millie', 'Finn', 'Gaten'],
    'age': [15, 16, 16],
    'city': ['London', 'Vancouver', 'New york']
}

Now, we need to import the pandas library and convert the Python dictionary to the DataFrame using the Pandas.dataframe() function.

See the following code.

# app.py

import pandas as pd

StrangerThings = {
    'name': ['Millie', 'Finn', 'Gaten'],
    'age': [15, 16, 16],
    'city': ['London', 'Vancouver', 'New york']
}

dataFrameObj = pd.DataFrame(StrangerThings)
print(dataFrameObj)

Output

➜  pyt python3 app.py
     name  age       city
0  Millie   15     London
1    Finn   16  Vancouver
2   Gaten   16   New york
➜  pyt

On Initialising the DataFrame object with this kind of dictionary, each item (Key / Value pair) in the dictionary will be converted to one column, i.e. key will become the Column Name and list in the Value field will be the column data.

All the keys in the dictionary will be converted to the column names and lists in each its value field will we converted to the column Data.

Covert Dict to DataFrame with custom indexes

We can also pass an index list to the DataFrame constructor to replace the default index list.

See the following code example.

# app.py

import pandas as pd

StrangerThings = {
    'name': ['Millie', 'Finn', 'Gaten'],
    'age': [15, 16, 16],
    'city': ['London', 'Vancouver', 'New york']
}

dataFrameObj = pd.DataFrame(StrangerThings, index=['m', 'f', 'g'])
print(dataFrameObj)

We have passed the index parameter with the list of m, f, g.

Output

➜  pyt python3 app.py
     name  age       city
m  Millie   15     London
f    Finn   16  Vancouver
g   Gaten   16   New york
➜  pyt

Create DataFrame from Dictionary

DataFrame constructor accepts the dictionary that should contain a list like objects in values.

But what if we have a dictionary that doesn’t have lists in value then how it gives an output.

Let’s understand with an example.

# app.py

import pandas as pd

StrangerThings = {
    'millie': 15,
    'finn': 16,
    'gaten': 16
}

dataFrameObj = pd.DataFrame(StrangerThings)
print(dataFrameObj)

Okay, now run the file.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 9, in <module>
    dataFrameObj = pd.DataFrame(StrangerThings)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 348, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 459, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 7315, in _arrays_to_mgr
    index = extract_index(arrays)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 7352, in extract_index
    raise ValueError('If using all scalar values, you must pass'
ValueError: If using all scalar values, you must pass an index
➜  pyt

It gives the ValueError: If using all scalar values, you must pass an index

So, the question is how to create a two-column DataFrame object from this kind of dictionary and put all keys and values as these separate columns.

For that, we will create a list of tuples (key / value) from this dictionary and pass it to another dataframe constructor that accepts the list.

See the following code.

# app.py

import pandas as pd

StrangerThings = {
    'millie': 15,
    'finn': 16,
    'gaten': 16
}

dataFrameObj = pd.DataFrame(
    list(StrangerThings.items()), index=['m', 'f', 'g'])
print(dataFrameObj)

Output

➜  pyt python3 app.py
        0   1
m  millie  15
f    finn  16
g   gaten  16
➜  pyt

That means we have created a dataframe from an unusual dictionary.

Create DataFrame from Dictionary and skip data

If we want to create the DataFrame object from the dictionary by skipping some of the items. Let’s see how to do that.

# app.py

import pandas as pd

StrangerThings = {
    'name': ['Millie', 'Finn', 'Gaten'],
    'age': [15, 16, 16],
    'city': ['London', 'Vancouver', 'New york']
}

dataFrameObj = pd.DataFrame(StrangerThings, columns=['name', 'city'])
print(dataFrameObj)

In the above code, we are passing the columns parameter, which holds the column names which we need to get while converting a dictionary to dataframe.

We can skip the columns by explicitly define the column names, which we need to include in the dataframe.

Output

➜  pyt python3 app.py
     name       city
0  Millie     London
1    Finn  Vancouver
2   Gaten   New york
➜  pyt

As in the columns parameter, we provided a list with only two column names. So, DataFrame should contain only two columns.

Create DataFrame from nested Dictionary

Let’s say we have the following dictionary.

StrangerThings = {
    0: {
        'name': 'Millie',
        'age': 15,
        'city': 'London'
    },
    1: {
        'name': 'Finn',
        'age': 16,
        'city': 'Vancouver'
    },
    2: {
        'name': 'Gaten',
        'age': 16,
        'city': 'New York'
    }
}

Let’s write the code that converts this nested Dictionary to DataFrame.

# app.py

import pandas as pd

StrangerThings = {
    0: {
        'name': 'Millie',
        'age': 15,
        'city': 'London'
    },
    1: {
        'name': 'Finn',
        'age': 16,
        'city': 'Vancouver'
    },
    2: {
        'name': 'Gaten',
        'age': 16,
        'city': 'New York'
    }
}

dataFrameObj = pd.DataFrame(StrangerThings)
dfObj = dataFrameObj.transpose()
print(dfObj)

In the above example, we used the DataFrame() and transpose() function to convert the nested dict to pandas dataframe.

The transpose() function of the matrix is used to swap the column with indexes so that data will be more readable with this.

Output

➜  pyt python3 app.py
  age       city    name
0  15     London  Millie
1  16  Vancouver    Finn
2  16   New York   Gaten
➜  pyt

So, we have seen multiple variations of creating the DataFrame from Dictionary.

Finally, How To Python Dictionary To DataFrame With Example is over.

Related Posts

Pandas set_index() example

Pandas value_counts() example

Pandas read_csv() example

Pandas boolean indexing example

Pandas sort_values() example

The post How To Python Dictionary To DataFrame Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/15/how-to-python-dictionary-to-dataframe-example/feed/ 0
How To Read File In Python Example | Python File Read https://appdividend.com/2019/11/15/how-to-read-file-in-python-file-open-and-read/ https://appdividend.com/2019/11/15/how-to-read-file-in-python-file-open-and-read/#respond Fri, 15 Nov 2019 09:50:04 +0000 http://localhost/wordpress/?p=12378 How To Read File In Python Example| Python File Read

In Python, there is no need to import an external library to read and write files. Python provides the inbuilt function for creating, writing, and reading files. In this tutorial, we will see how to read file in Python. First, we will see how to open a file using Python open() function and then read […]

The post How To Read File In Python Example | Python File Read appeared first on AppDividend.

]]>
How To Read File In Python Example| Python File Read

In Python, there is no need to import an external library to read and write files. Python provides the inbuilt function for creating, writing, and reading files. In this tutorial, we will see how to read file in Python.

First, we will see how to open a file using Python open() function and then read the files. Before we start reading the file, let’s understand how to create a file in Python, and then we will write and read the file.

Python Create File

We can create a new file in Python using the open() method, with one of the following parameters:

“x” – Create – will create the file, returns an error if the file exists.

“a” – Append – will create the file if the specified file does not exist.

“w” – Write – will create the file if the specified file does not exist.

See the following code.

# app.py

f = open("data.txt", "a")

The above code creates a file if the file does not exist.

Now, let’s write two lines in the file.

Python Write File

In this blog, I have already written how to write a file in Python.

We will use the Python writelines() method to write in a file.

Python file method writelines() writes the sequence of strings to the file.

The sequence can be any iterable object producing strings, typically the list of strings. There is no return value.

Python’s writelines() method writes the items of the list to the file.

Where the texts will be inserted depends on the file mode and stream position.

  1. “a”: The texts will be inserted at a current file stream position, default at the end of the file.
  2. “w”: The file will be emptied before the texts will be inserted at the current file stream position, default 0.

See the following code to write a file.

# app.py

f = open("data.txt", "a")
f.writelines(["\nSee you soon!", "\nPeek-a-boo."])
f.close()

After you run the above code, you will get the file named data.txt with the following content.

# data.txt

See you soon!
Peek-a-boo.

The next step is to open and read a file.

Python Open and Read File

We can open the file using a built-in open() function.

The open() function returns the file object that has a read() method for reading the content of the file.

We have a file called data.txt, which has the following content written in it.

See you soon!
Peek-a-boo.

Now, we will open this file using the following code.

f = open('data.txt', 'r')

Now, read the content and print it on the console.

# app.py

f = open('data.txt', 'r')
print(f.read())

Output

➜  pyt python3 app.py
See you soon!
Over and out.
➜  pyt

How to read only parts of the File in Python

By default, Python read() method returns the whole text, but you can also specify how many characters you want to return.

Let’s say we have the following file named sample.txt. It has the following content.

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11

Now, let’s say we want to read the first 14 characters from the above file.

To achieve that output, we can pass the parameter in the read function.

# app.py

f = open('sample.txt', 'r')
print(f.read(14))

Output

➜  pyt python3 app.py
This is line 1
➜  pyt

Python Read Lines

You can return one line by using the readline() method.

# app.py

f = open('sample.txt', 'r')
print(f.readline())

Output

➜  pyt python3 app.py
This is line 1

➜  pyt

By calling readline() two times, you can read the two first lines.

# app.py

f = open('sample.txt', 'r')
print(f.readline())
print(f.readline())

Output

➜  pyt python3 app.py
This is line 1

This is line 2

➜  pyt

Python readlines()

Python file method readlines() reads until EOF using the readline() and returns the list containing the lines.

If the optional sizehint argument is present, instead of reading up to EOF, whole lines totaling approximately sizehint bytes (possibly after rounding up to the internal buffer size) are read.

The empty string is returned only when EOF is encountered immediately.

See the following example.

# app.py

f = open('sample.txt', 'r')
print(f.readlines())

Output

➜  pyt python3 app.py
['This is line 1\n', 'This is line 2\n', 'This is line 3\n', 'This is line 4\n', 'This is line 5\n', 'This is line 6\n', 'This is line 7\n', 'This is line 8\n', 'This is line 9\n', 'This is line 10\n', 'This is line 11']
➜  pyt

When you run the code for reading the file or document line by line, it will separate each line and present the file in the readable format.

But if there is a complex data file which is not readable, this piece of code could be useful.

Read data using for loop

By looping through the lines of the file, you can read the whole file, line by line.

# app.py

f = open('sample.txt', 'r')
for x in f:
    print(x)

Output

➜  pyt python3 app.py
This is line 1

This is line 2

This is line 3

This is line 4

This is line 5

This is line 6

This is line 7

This is line 8

This is line 9

This is line 10

This is line 11
➜  pyt

Opening and closing a file with try-catch block

When you want to work with a file, the first thing to do is to open it. This is done by invoking the open() built-in function. open() has a single required argument that is the path to the file. The open() has a single return, the file object:

f = open('data.txt')

After you open a file, the next thing to learn is how to close it.

Warning: You should always make sure that an open file is closed correctly.

It’s important to remember that it’s your responsibility to close the file. In most cases, upon the termination of an application or script, a file will be closed eventually.

However, there is no guarantee when exactly that will happen. This can lead to unwanted behavior, including resource leaks.

It’s also a best practice within Python (Pythonic) to make sure that your code behaves in a way that is well defined and reduces any unwanted behavior.

When you’re manipulating the file, there are two ways that you can use to ensure that a file is closed correctly, even when encountering an error. The first way to close a file is to use the try-finally block.

See the following code.

# app.py

try:
    f = open('sample.txt', 'r')
    print(f.readlines())
finally:
    f.close()

If you’re unfamiliar with what the try-finally block is, check out Python Exceptions.

Python with statement

In Python, the “with statement“, you get better syntax and exceptions handling. 

Python with statement simplifies exception handling by encapsulating standard preparation and cleanup tasks. Also, it will automatically close the file.

Python “with statement” provides a way for ensuring that a clean-up is always used.

See the following code.

# app.py

with open('sample.txt') as reader:
  data = reader.read()
  print(data)

Output

➜  pyt python3 app.py
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11
➜  pyt

The with statement automatically takes care of closing the file once it leaves the with the block, even in cases of error.

You can use a with statement as much as possible, as it allows for cleaner code and makes handling any unexpected errors easier for you.

Finally, How To Read File In Python Example | Python File Read Tutorial is over.

Related Posts

File handling in Python

Write Python dictionary to CSV

The post How To Read File In Python Example | Python File Read appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/15/how-to-read-file-in-python-file-open-and-read/feed/ 0
How To Write Python Dictionary To CSV File Example https://appdividend.com/2019/11/14/how-to-write-python-dictionary-to-csv-example/ https://appdividend.com/2019/11/14/how-to-write-python-dictionary-to-csv-example/#respond Thu, 14 Nov 2019 10:58:18 +0000 http://localhost/wordpress/?p=12367 How To Write Python Dictionary To CSV Example

In this tutorial, we will see How To Convert Python Dictionary To CSV File Example. CSV (Comma Separated Values) is the most common file format that is widely supported by many platforms and applications. Use the CSV module from Python’s standard library. The easiest way is to open a CSV file in ‘w’ mode with […]

The post How To Write Python Dictionary To CSV File Example appeared first on AppDividend.

]]>
How To Write Python Dictionary To CSV Example

In this tutorial, we will see How To Convert Python Dictionary To CSV File Example. CSV (Comma Separated Values) is the most common file format that is widely supported by many platforms and applications. Use the CSV module from Python’s standard library.

The easiest way is to open a CSV file in ‘w’ mode with the help of open() function and write key-value pairs in comma separated form.

Python Dictionary to CSV

Okay, first, we need to import the CSV module.

import csv

Next, we will define a dictionary.

import csv

dict = {'name': 'krunal', 'age': 26, 'education': 'Engineering'}

Now, we use the open() function to open a file in the writing mode and use the dictionary.keys() method to write the CSV data into the file.

See the following code.

# app.py

import csv

dict = {'name': 'krunal', 'age': 26, 'education': 'Engineering'}

with open('data.csv', 'w') as f:
    for key in dict.keys():
        f.write("%s, %s\n" % (key, dict[key]))

Output

name, krunal
age, 26
education, Engineering

The CSV module contains the DictWriter method that requires the name of the CSV file to write and a list object containing field names.

The writeheader() method writes the first line in CSV file as field names. The subsequent for loop write each row in CSV form to the CSV file.

More Examples

Let’s write more data in the CSV file.

See the following code.

# app.py

import csv

csv_columns = ['Service', 'ShowName', 'Seasons']
dict = [
    {'Service': 'Netflix', 'ShowName': 'Stranger Things', 'Seasons': 3},
    {'Service': 'Disney+', 'ShowName': 'The Mandalorian', 'Seasons': 1},
    {'Service': 'Hulu', 'ShowName': 'Simpsons', 'Seasons': 31},
    {'Service': 'Prime Video', 'ShowName': 'Fleabag', 'Seasons': 2},
    {'Service': 'AppleTV+', 'ShowName': 'The Morning Show', 'Seasons': 1},
]
csv_file = "data.csv"
try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        writer.writeheader()
        for data in dict:
            writer.writerow(data)
except IOError:
    print("I/O error")

Output

Service,ShowName,Seasons
Netflix,Stranger Things,3
Disney+,The Mandalorian,1
Hulu,Simpsons,31
Prime Video,Fleabag,2
AppleTV+,The Morning Show,1

We are using DictWriter.writerow() to write a single row.

We have used DictWriter.writeheader() if you want a header for your CSV file.

Also, we have used “with statement” for opening files. It’s not only more pythonic and readable but handles the closing for you, even when exceptions occur.

So, in the above example, we have used the following Python CSV functions.

Python CSV.DictWriter()

It creates the object which operates like the regular writer but maps the dictionaries onto output rows.

The fieldnames parameter is the sequence of keys that identify an order in which values in a dictionary passed to the writerow() method are written to file f.

The optional restval parameter specifies the value to be written if a dictionary is missing the key in fieldnames.

If a dictionary passed to the writerow() method contains a key not found in fieldnames, an optional extrasaction parameter indicates what action to take.

If it is set to ‘raise’, the default value, a ValueError is raised.

If it is set to ‘ignore’, extra values in the dictionary are ignored.

Any other optional or keyword arguments are passed to an underlying writer instance.

Python DictWriter.writeheader()

This function is used to write a row with the field names (as specified in the constructor) to the writer’s file object, formatted according to the current dialect. Return the return value of the csvwriter.writerow() call used internally.

Python csvwriter.writerow(row)

The function is used to write the row parameter to the writer’s file object, formatted according to the current dialect. The return value of the call to the write method of the underlying file object.

Python csvwriter.writerows(rows)

This function is used to write all items in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.

Finally, How To Write Python Dictionary To CSV Example is over.

Related Posts

Python CSV Example

How to write a file in Python

Pandas dataframe read_csv Example

The post How To Write Python Dictionary To CSV File Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/11/14/how-to-write-python-dictionary-to-csv-example/feed/ 0