Python String
A string represents the group of characters. String are important because most of the data we use in daily life will be in the form of string. Example: name of the person, the address etc.
In python str datatype represents a string.
Since every string comprises several characters, python handles string and characters almost the same manner. There is no separate datatype to represent individual characters in python.
Creating Strings
We can create a string in python by assigning a group of characters to a variable. The group of characters should be enclosed inside single, double or triple quotes as shown in an example:
S1= ‘Welcome to pythonior.com’
S2= “Welcome to pythonior.com”
S3=“‘Welcome to pythonior.com”’
It is possible to display quotation marks to mark a substring in a string.
In this case you should use one type of quotes for outer string and another type of quotes for inner string as:
S1 = ‘ welcome to “ python” tutorial’
print( S1)
Output:
welcome to “ python” tutorial
Here, The string ‘ S1’ contains two strings. The outer string is enclosed in a single quotes and the inner string is enclosed in double quotes.
It is possible to use escape characters like \t or \n inside the strings. The escape character \t releases tab space and \n is for new line.
Example:
S1 = “welcome to \tpython \ntutorial”
print(S1)
Output:
welcome to python
tutorial
Escape character and their meanings
Escape character
|
Meaning
|
\a
|
Bell or alert
|
\b
|
Backspace
|
\n
|
New line
|
\t
|
Horizontal tab space
|
\v
|
Vertical tab space
|
\r
|
Enter button
|
\x
|
Character x
|
\\
|
Display single \
|
To nullify the effect of ecape characters, we can create the string as a 'raw' string by adding 'r' before the string as:
S1 = r“welcome to \tpython \ntutorial”
print(S1)
Output
welcome to \tpython \ntutorial
This is not showing the sffect of \t or \n. Raw string take escape characters like \t or \n as ordinary characters and display them as they are.
Length of String
Length of the string represents number of characters in the string. len() function is used to know the length of a string.
This function gives the number of characters including spaces in the string.
str = 'Python Tutorial'
n = len(str)
print(n)
Output:
15
Indexing in String
Index represents the position number. Index is written using square braces []. By specifying the position number through an index, we can refer to the individual elements (or characters) of a string. When we use index as a negative number, it refers to elements in the reverse order.
![]() |
Indexing in String |
Slicing the String
A slice represents a part or piece of a string.
Syntax:
stringname[start: stop: stepsize]
If 'start' and 'stop' are not specified, then slicing is done from 0th to (n-1)th elements. If 'stepsize' is not given, then it takes as 1.
Example1:
str = 'Core Python'
str[0:9:1] #access string from 0 to 8th element in step of 1.
Output:
Core Pyth
Example2:
str = 'Core Python'
str[0:9:2] #access string from 0 to 8th element in step of 2.
Output:
Cr yh
Example:
str = 'Pythonior'
print(str*2)
Output:
PythoniorPythonior
Syntax:
stringname[start: stop: stepsize]
If 'start' and 'stop' are not specified, then slicing is done from 0th to (n-1)th elements. If 'stepsize' is not given, then it takes as 1.
Example1:
str = 'Core Python'
str[0:9:1] #access string from 0 to 8th element in step of 1.
Output:
Core Pyth
Example2:
str = 'Core Python'
str[0:9:2] #access string from 0 to 8th element in step of 2.
Output:
Cr yh
Repeating the Strings
The repetition operator is denoted by '*' symbol and is useful to repeat the string for several times. For example *n repeats the string for n times.Example:
str = 'Pythonior'
print(str*2)
Output:
PythoniorPythonior
Concatenation of Strings
We can use '+' on strings to attach a string at the end of another string. This operator '+' is called addition operator when used on numbers. But, when used on strings, it is called 'concatenation' operator since it joins the strings. Similar results can be achieved using the join() method also.
Example:
s1 = 'core'
s2 = "Python"
s3 = s1 + s2 #concatenate s1 and s2
print(s3) #display the total string s3
Output:
corePython
Example:
s1 = 'core'
s2 = "Python"
s3 = s1 + s2 #concatenate s1 and s2
print(s3) #display the total string s3
Output:
corePython
Checking Membership
We can check if a string or character is a member of another string or not using 'in' or 'not in' operators.
The 'in' operator returns True if the string or character is found in the main string. It returns False if the string or character is not found in the main string.
The 'not in' operator returns False if the string or character is not found in the main string otherwise True.
Example:
#to know whether sub string is in main string or not
str = input('Enter main string: ')
sub = input('Enter sub string: ')
if sub in str:
print(sub+ 'is found in main string')
else:
print(sub+ 'is not found in main string')
Output:
Enter main string: This is Pythonior
Enter sub string: Pythonior
Pythonior is found in main string
Comparing Strings (Substring)
We can use the relational operators like >, >=, <, <=, == or != operators to compare two strings. The return Boolean values, i.e. either True or False depending on the string being compared.
Example:
s1 = 'Box'
s2 = 'Boy'
if (s1 == s2):
print('Both are same')
else:
print('Not same')
Output:
Not same
While comparing the strings, Python interpreter compares them by taking them in English dictionary order.
The string which comes first in the dictionary order will have a low value than the string which comes next.
In the above example, the string s1 comes before the string s2 and hence s1 is less than s2. So, if we write:
if s1<s2:
print('s1 is less than s2')
else:
print('s1 is greater than or equal to s2')
Output:
s1 is less than s2
Replacing a String with another String
The replace() method is useful to replace a sub string in a string with another sub string.
Syntax:
stringname.replace(old, new)
This will replace all the occurrences of 'old' sub string with the 'new' sub string in the main string.
Example:
str = 'That is a beautiful flower'
s1 = 'flower'
s2 = 'girl'
str1 = str.replace(s1, s2)
print(str)
print(str1)
Output:
That is a beautiful flower
That is a beautiful girl
Splitting and Joining Strings
The split() method is used to brake a string into pieces. This pieces are returned as a list.
Syntax:
stringname.split(' , ')
The comma inside the parentheses is called separator that represents where to separate or cut the string.
Example:
str = 'one , two, three, four'
str1 = str.split(' , ')
print(str1)
Output:
['one' , 'two', 'three' , 'four']
Formatting the Strings
Formatting a string means presenting the string in a clearly understandable manner. The format() method is used to format strings.
Syntax:
'format string with replacement fields' . format(values)
Let's first understand the meaning of 'format string with replacement fields'
The replacement fields are denoted by curly braces{} that contains names or indexes. These names or indexes represent the order of the values.
Let's take an employee details like id number, name and salary in 3 variables like 'id' , 'name' , and 'sal'.
id = 10
name = 'shankar'
sal = 19500
We want to create a format string by the name 'str' to display these 3 values. These 3 values or variables should be mentioned inside the format() method as format(id,name,sal)
str = '{},{},{}'.format(id,name,sal)
print(str)
In this first field{} is replaced by 'id' value and the second field{} is replaced by 'name' value and the third field{} is replaced by 'sal' value.
Output:
10,shankar,19500
Points to Remember
- A string represents a group of characters
- We can create strings by assigning a group of characters to a variable.
- There is no difference between single quotes and double quotes while writing the string.
- Triple double quotes or triple single quotes are useful to extend the string beyond several lines.
- The len() function gives the length or number of character in a string.
- Indexing and slicing are the two ways to access elements or characters of a string.
- Index is an integer that represents the position number of the element in the string. It is written in the form of str[i].
- Slicing represents a part or piece of the string. It is written in the form of str[start: stop: stepsize].
- Concatenation of strings can be done using '+' operator or join() method.
- The 'in' and 'not in' operators are used to check if a sub string is found in the main string or not. They return Boolean value, i.e. either True or False.
- Relational operators like >, >=, <, <=, == or != operators to compare two strings. The return Boolean values, i.e. either True or False.
- The replace() method is useful to replace a sub string in a string with another sub string.
- The split() method is used to brake a string into pieces.
- The format() method is used to format strings.
I have read your blog it is very helpful for us. I couldn't find any knowledge on this matter prior to. I would like to thanks for sharing this article here. Python classes in jaipur
ReplyDelete