Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example :
a = "Hello, World!"
Let's try some examples for accessing a string with some basic functions :
Note : Strings can be output to screen using the print() function and remember that the first character has the position 0.
Python includes many built-in methods but here we just adding some of the following built-in methods to manipulate strings :
Python allows for command line input. That means we are able to ask the user for input. The following example asks for the user's name, then, by using the input() function method, the program prints the name to the screen:
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
|Backslash notation||Hexadecimal character||Description|
|\a||0x07||Bell or alert|
Assume string variable a = "Hello" and variable b = "Python", then :
|+||Concatenation||a + b will give - HelloPython|
|*||Repetition||a*2 will give - HelloHello|
|||Slice||a will give - e|
|[ : ]||Range Slice||a[1:4] will give - ello|
|in||Membership - if a character exists||a in b will give - False|
|not in||Membership - if a character does not exist||a not in b will give - True|
|%||Format - Performs String formatting, we learn this at next section.|
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example :
print("My name is %s and age is %d." % ('AyaN', 24))
Output Result :
My name is AyaN and age is 24.
Here is the list of complete set of symbols which can be used along with % :
|%i||signed decimal integer|
|%d||signed decimal integer|
|%u||unsigned decimal integer|
|%x||hexadecimal integer (lowercase letters)|
|%X||hexadecimal integer (UPPERcase letters)|
|%e||exponential notation (with lowercase 'e')|
|%E||exponential notation (with UPPERcase 'E')|
|%f||floating point real number|
|%g||the shorter of %f and %e|
|%G||the shorter of %f and %E|
Python triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.
It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.