In the previous article we saw how could obtain the prime factors of a number, now we will examine the role of Strings in Python.
A string consists of a sequence of characters, it is typically used to store text data. Any other object in Python can be translated to the string that matches it. To do this, you need to call the function
str(), passing it an object translated into a string as a parameter. Strings in Python can be particularly useful when dealing with text files. The alphabetical data stored in strings is according to the ASCII(American Standard Code for Information Interchange) structure. Python however typically refers to the UNICODE standard when possible which also includes some of the ASCII codes.
Here is a program on Strings in Python:
print(ord("a")) print(ord("A")) print(chr(97)) print(chr(65))
Output: 97 65 a A
The ord function returns the integer representation of the character passed to it, meanwhile the chr( ) function returns the alphabet associated with the number.
Further programs on Strings in Python
Let us see a program for accessing various elements of a string:
s="geek" print(s) print(s) print(s[-1]) print(s) print(s[-2])
Output: geek g k e e
An index of negative numbers starts backwards from the last digit.
Program to demonstrate immutability of Strings in Python
s="geek" s="e" print(s)
Output: Traceback (most recent call last): File "main.py", line 2, in <module> s="e" TypeError: 'str' object does not support item assignment
Similar to Java, Strings in Python cannot be modified after the initialization and value is declared.
Program to demonstrate Triple Quote or Multi-line Strings in Python
Here we create a string, and then use triple quotes
s="""Hi, This is a Python Article, Hope you are enjoying it!""" print(s)
Output: Hi, This is a Python Article, Hope you are enjoying it!
We can also use single quote thrice, to form these kind of strings.
In the next article, we will look at Escape Sequences and Raw Strings in Python.