Friday, March 30, 2018

How to check alphanumeric characters in Python Strings ?


String isalnum() Method

 The isalnum() method checks whether the string consists of alphanumeric characters.

Syntax

str.isa1num()

Return Value

This method returns true if all the characters in the string are alphanumeric and there is at least one character, false otherwise.

Example

#!/usr/bin/python3
str = "this2016"    # No space in this string
print (str.isalnum())

str = "this is string example....wow!!!"
print (str.isalnum())

 When we run the above program, it produces the following result-

True
False




<<< index( )                                Go to Index                        isalpha( ) >>>



How to index a string in Python 3 ?


String index( ) Method

 The index() method determines if the string str occurs in string or in a substring of string,if the starting index beg and ending index end are given. This method is same as find(),but raises an exception if sub is not found.

Syntax

str.index(str, beg=0 end=len(string))

Parameters

· str - This specifies the string to be searched.
· beg - This is the starting index, by default its 0.
· end - This is the ending index, by default its equal to the length of the string.

Return Value

Index if found otherwise raises an exception if str is not found.

Example

#!/usr/bin/python3
str1 = "this is string example....wow!!!"
str2 = "exam";
print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))

Result

15
15
Traceback (most recent call last):
    File "test.py", line 7, in
      print (str1.index(str2, 40))
ValueError: substring not found
shell returned 1




<<< find( )                           Go to Index                          isalnum( ) >>>





How to find a string in Python Strings ?


String find( ) Method

 The find() method determines if the string str occurs in string, or in a substring of string if the starting index beg and ending index end are given.

Syntax

str.find(str, beg=0 end=len(string))

Parameters

· str - This specifies the string to be searched.
· beg - This is the starting index, by default its 0.
· end - This is the ending index, by default its equal to the length of the string.

Return Value

Index if found and -1 otherwise.

Example

#!/usr/bin/python3

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))

Result

15
15
-1



<<< expandtabs( )                    Go to Index                  index( ) >>>





How to expandtabs( ) in Python Strings?


String expandtabs( ) Method

 The expandtabs() method returns a copy of the string in which the tab characters ie. '\t' are expanded using spaces, optionally using the given tabsize (default 8)..

Syntax

str.expandtabs(tabsize=8)

Parameters
tabsize - This specifies the number of characters to be replaced for a tab character '\t'.

Return Value
This method returns a copy of the string in which tab characters i.e., '\t' have been expanded using spaces.

Example

#!/usr/bin/python3
str = "this is\tstring example....wow!!!"
print ("Original string: " + str)
print ("Defualt exapanded tab: " + str.expandtabs())
print ("Double exapanded tab: " + str.expandtabs(16))
   

Result

Original string: this is string example....wow!!!
Defualt exapanded tab: this is string example....wow!!!
Double exapanded tab: this is string example....wow!!!



<<< endswith( )                  Go to Index                    find( ) >>>





How to use endswith( ) method in Strings ?


String endswith( ) Method

 It returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end.

Syntax

str.endswith(suffix[, start[, end]])

Parameters
· suffix - This could be a string or could also be a tuple of suffixes to look for.
· start - The slice begins from here.
· end - The slice ends here.

Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.

 Example

#!/usr/bin/python3

Str='this is string example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))

Result

True
True
False
True



<<< encode( )                         Go to Index                   expandtabs( ) >>>


How to encode a String in Python ?


String encode( ) Method

 The encode() method returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme.

Syntax

str.encode(encoding='UTF-8',errors='strict')


Parameters
· encoding - This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings.
· errors - This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().

Return Value
          Decoded string.

Example

#!/usr/bin/python3

import base64

Str = "this is string example....wow!!!"
Str=base64.b64encode(Str.encode('utf-8',errors='strict'))

print ("Encoded String: " , Str)

Result

Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='



<<< decode( )                       Go to Index                endswith( ) >>>



Thursday, March 29, 2018

How to decode a String in Python 3 ?


String decode( ) Method

The decode() method decodes the string using the codec registered for encoding. It defaults to the default string encoding.

Syntax

Str.decode(encoding='UTF-8',errors='strict')

Parameters
· encoding - This is the encodings to be used. For a list of all encoding schemes
please visit: Standard Encodings.

· errors - This may be given to set a different error handling scheme. The default
for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error()..

Return Value
          Decoded string.

Example

#!/usr/bin/python3
Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print ("Encoded String: " + Str)
print ("Decoded String: " + Str.decode('base64','strict'))

Result
Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='
Decoded String: this is string example....wow!!!



<<< count( ) method                   Go to Index                   encode( ) >>>

How to write count( ) method in Python 3 ?


String count( ) Method

The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

Syntax


str.count(sub, start= 0,end=len(string))

Parameters
· sub - This is the substring to be searched.
· start - Search starts from this index. First character starts from 0 index. By default
search starts from 0 index.
· end - Search ends from this index. First character starts from 0 index. By default
search ends at the last index.

Return Value
Centered in a string of length width.

Example

#!/usr/bin/python3
str="this is string example....wow!!!"
sub='i'
print ("str.count('i') : ", str.count(sub))
sub='exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))

Result
str.count('i') : 3
str.count('exam', 4, 40) :



<<< center( ) method                  Go to Index                  decode( ) >>>


How to center a String in Python 3 ?


String center( ) Method

The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.

Syntax

str.center(width[, fillchar])

Parameters
· width - This is the total width of the string.
· fillchar - This is the filler character.


Return Value
This method returns a string that is at least width characters wide, created by padding the string with the character fillchar (default is a space).

Example

#!/usr/bin/python3
str = "this is string example....wow!!!"

print ("str.center(40, 'a') : ", str.center(40, 'a'))

Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa



<<< capitalize ( )                    Go to Index                        count( ) >>>


How to capitalize a string in Python 3 ?


String capitalize( ) Method

It returns a copy of the string with only its first character capitalized.

Syntax

str.capitalize()


Return Value
     string

Example


#!/usr/bin/python3
str = "this is string example....wow!!!"

print ("str.capitalize() : ", str.capitalize())

Result

str.capitalize() : This is string example....wow!!!



<<< Unicode Strings                    Go to Index                center( ) >>>


Tuesday, March 27, 2018

Compare Sets


Compare Sets

We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)

When the above code is executed, it produces the following result.

True
True



<<< Difference of Sets                      Go to Index               Nodes >>>




Difference of Sets


Difference of Sets

The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])

AllDays = DaysA – DaysB

print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Mon', 'Tue'])



<<< Intersection of Sets                              Go to Index                  Compare Sets >>>