Comparing Strings

 Computer internally stores characters as numbers.

Every character has a unique Unicode value.

Ord

To find the Unicode value of a character, we use the

ord()

ord(character)
gives unicode value of the character.

Code

unicode_value = ord("A")
print(unicode_value)
PYTHON

Output

65

chr

To find the character with the given Unicode value, we use the

chr()

chr(unicode)
gives character with the unicode value.

Code

char = chr(75)
print(char)
PYTHON

Output

K

Unicode Ranges

48 - 57 -> Number Digits (0 - 9)

65 - 90 -> Capital Letters (A - Z)

97 - 122 -> Small Letters (a - z)

Rest -> Special Characters, Other Languages

Printing Characters

The below code will print the characters from

A
to
Z

Code

for unicode_value in range(65,91):
print(chr(unicode_value))
PYTHON

Output

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
Collapse

Comparing Strings

In Python, strings are compared considering unicode.

Code

print("A" < "B")
PYTHON

Output

True

As unicode value of

A
is 65 and
B
is 66, which internally compares
65 < 66
. So the output should be
True

Character by Character Comparison

In Python, String Comparison is done character by character.

Code

print("BAD" >= "BAT")
PYTHON

Output

False

Code

print("98" < "984")
PYTHON

Output

True

Best Practices

Naming Variables Rule #1

Use only the below characters

  • Capital Letters ( A – Z )
  • Small Letters ( a – z )
  • Digits ( 0 – 9 )
  • Underscore(_)

    Examples:
    age, total_bill

Naming Variables Rule #2

Below characters cannot be used

  • Blanks ( )
  • Commas ( , )
  • Special Characters
    ( ~ ! @ # $ % ^ . ?, etc. )

Naming Variables Rule #3

Variable name must begin with

  • Capital Letters ( A – Z )
  • Small Letters ( a – z )
  • Underscore( _ )

Naming Variables Rule #4

Cannot use Keywords, which are reserved for special meaning

  • int
  • str
  • print
     etc.,

Keywords

Words which are reserved for special meaning

Code

help("keywords")
PYTHON

Output

Here is a list of the Python keywords. Enter any keyword to get more help.
False break for not
None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
None
 
Collapse

Case Styles

  • Camel case: totalBill
  • Pascal case: TotalBill
  • Snake case: total_bill

Snake case is preferred for naming the variables in Python.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form