Followers

Friday, December 6, 2019

Size of Strings - String Literals

Size of Strings

Today we will talk about the Size of Strings. It's going to bit longer as size of strings is very important in python. 
Python determines the size of a string as the count of characters in the strings. For Example, size of string "XYZ" is 3 and of "strings" is 7. But if your string literals have an Escape sequence contained within it then make sure to count the Escape sequence as one character. Consider some examples given below, 

'\\'                    -  Size is 1 (\\; is an escape sequence to represent backslash)
'XYZ'                -  Size is 3
"\abc"              - Size is 2 (\a is an escape sequence thus 1 character)
"Sony\'s pen"  - Size is 10 (For typing apostrophe, and for using \' escape sequence)
"Any's"           - Size is 4 (Python allows a single quote without escape sequence in                                   double-quoted string and vice versa.

For Multiple Strings created with triple quotes, while calculating the size, the EOL(end-of-line)characters at the end of line is also counted in the size. For example,
Str3 = '''a↲ 
b↲
c'''
In the above Example "↲" this sign is the sign of End of Line character and counted in the length of Multiple line string.
Str4 = '''He\
ll\
o'''
But in this case, the Backslash(\) at end of the intermediate line of  Multiple line string will not be counted. 
Therefore the size of Str3 is 5 (three characters a,b,c and two EOL characters)
For Multiple line string created with single/double quotes and Backslash character at end of the Line, while calculating size, the backslashes are not counted in the size of the string; also you cannot put EOLs using return key in single/double quoted Multiple line string. Example 
Str4 = 'a\
b\
c'
The size of strings Str4 is 3 (only  3 characters, no backslash counted). 
To check the size of a string, you may also type len(<stringname>) Command on the Python prompt in console window shell. 


So with this we are end with this Post. Don't Forget To Follow Me on Bloggers to get my latest Post Updates about Python. 
JAI HIND!!! 
VANDE MATARAM!!!!!

No comments:

Post a Comment

If you have any doubts, please do let me Know.