Sunday, March 26, 2017

String handling in Python

A string in python can be declared simply as:

>>> first_string="Pythonidae"
>>> print first_string
Pythonidae


Strings are immutable in python. That means you cannot change the string by accessing it with index.

>>> first_string[2]='m'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

Also in python if you make a string the id function always returns same unique id if the strings are same

>>> first_string = "Pythonidae"
>>> second_string = "Pythonidae"
>>> third_string = "Cobra"
>>> id(first_string)
4329477440
>>> id(second_string)
4329477440
>>> id(third_string)

4329477248

Length of String

>>> len(first_string)
10
>>> len(third_string)

5

Looping over String - character by character

>>> for index in range(0,len(first_string)):
...   print first_string[index]
... 
P
y
t
h
o
n
i
d
a
e

Looping can be done in a simple way also

>>> for alphabet in first_string:
...   print alphabet
... 
P
y
t
h
o
n
i
d
a
e

You can use a while looping also

>>> index = 0
>>> while index < len(third_string):
...   print third_string[index]
...   index += 1
... 
C
o
b
r
a

String Slicing

# Print 0,1,2 characters. Note this excludes the 3rd index
>>> first_string[0:3]
'Pyt'

#Print 2,3,4
>>> first_string[2:5]
'tho'

#Valid slicing 
>>> first_string[-1:-3]
''

# Valid slicing. Read backwards as -1,-2,-3
# will print -3 and -2
>>> first_string[-3:-1]
'da'

String module

String module contains many utility functions which can help in doing many routine operations. It contains a lot of constants also which can be useful. To use string functions import the string module

>>> import string
>>> string.punctuation

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

Formatting 

The positional formatter can replace the placeholders

>>> "My name is {}. My version is {}".format("Python",sys.version_info)

"My name is Python. My version is sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)"

Comparison

String supports comparison for both equality and greater than and less than

>>> first_word = "apple"
>>> second_word = "Apple"

>>> third_word = "apple"

#case matters
>>> if first_word != second_word:
...   print True
... 
True

#Exact match is what it will say True
>>> if first_word == third_word:
...   print True
... 
True

#small letters are bigger than capital ones. For a change
>>> if first_word > second_word:
...   print True
... 
True


No comments:

Post a Comment