python Concept of String String manipulating & Indexing Creating String & Deleting String Various String Functions by unitdiploma
p
- Concept of String.
- String manipulating & Indexing
- Creating String & Deleting String
- Various String Functions
String
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0’s and 1’s.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Example:
str=”Nielit”
print(type(str))
Output:
<class ‘str’>
In Python, strings are treated as the sequence of characters, which means that Python doesn’t support the character data-type; instead, a single character written as ‘N’ is treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.
Example:
#Use single quotes
s1 = ‘Python Programming’
print(s1)
print(type(s1))
print(“***********************”)
#Use double quotes
s2 = “Python Programming”
print(s2)
print(type(s2))
print(“***********************”)
#Use triple quotes
s3 = ””’Triple quotes are generally used for
represent the multiline or
docstring”’
print(s3)
print(type(s3))
Output
Python Programming
<class ‘str’>
***********************
Python Programming
<class ‘str’>
***********************
”Triple quotes are generally used for
represent the multiline or
docstring
<class ‘str’>
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, the string “HELLO” is indexed as given in the below figure.
Example
str = “PYTHON”
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[5])
# It returns the IndexError because 6th index doesn’t exist
print(str[6])
Output
P
Y
T
H
O
N
IndexError: string index out of range
Slice operator [] in String
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the: (colon) operator in Python to access the substring from the given string.
Example
Example
str =’HELLOWORLD’
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
# Search Character out of index
print(str[-12])
Output
D
R
LD
ORL
LOWOR
DLROWOLLEH
print(str[-12])
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn’t support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
Example
str = “PYTHON”
str[0] = “p”
print(str)
Output
str[0] = “p“
TypeError: ‘str’ object does not support item assignment
Example
str = “PYTHON”
print(str)
str= “python”
print(str)
output:
PYTHON
python
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can delete the entire string using the del keyword.
str=”PYTHON”
print(str)
del str[0]
#print String after delete
print(“*******”)
print(str)
Output:
del str[0]
TypeError: ‘str’ object doesn’t support item deletion
Example
str=”PYTHON”
print(str)
del str
#print String after delete
print(“*******”)
print(str)
Output:
PYTHON
*******
<class ‘str’>
String Operators
Operator | Description |
+ | It is known as concatenation operator used to join the strings given either side of the operator. |
* | It is known as repetition operator. It concatenates the multiple copies of the same string. |
[] | It is known as slice operator. It is used to access the sub-strings of a particular string. |
[:] | It is known as range slice operator. It is used to access the characters from the specified range. |
in | It is known as membership operator. It returns if a particular sub-string is present in the specified string. |
not in | It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string. |
% | It is used to perform string formatting. It makes use of the format specifies used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python. |
Example on String Operator:
str1 = “Python”
str2 = “Program”
print(str1*3) # prints PythonPythonPython
print(str1+str2)# prints PythonProgram
print(str1[4]) # prints o
print(str2[2:4]); # prints og
print(‘h’ in str1) # prints True as “h” is present in str1
print(‘m’ in str1) # prints False as “m” is not present in str1
print(‘am’ not in str2) # prints False as “am” is present in str2.
print(‘n’ not in str2) # prints True as “n” is not present in str2.
print(“The string str : %s”%(str1)) # prints The string str : Python
Output
PythonPythonPython
PythonProgram
o
og
True
False
False
True
The string str : Python
String Functions
1.count()
The count() method returns the number of times a specified value appears in the string.
Syntax: string.count(value, start, end)
Parameter | Description |
value | Required. A String. The string to value to search for |
start | Optional. An Integer. The position to start the search. Default is 0 |
end | Optional. An Integer. The position to end the search. Default is the end of the string |
Example: Return the number of times the value “apple” appears in the string:
txt = “I love apples, apple are my favorite fruit”
x = txt.count(“apple”)
print(x)
Output: 2
Example: Search from index 10 to 24:
txt = “I love apples, apple are my favorite fruit”
x = txt.count(“apple”, 10, 24)
print(x)
Output: 1
2.find()
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
Syntax: string.find(value, start, end)
Parameter | Description |
Value | Required. The value to search for |
Start | Optional. Where to start the search.Default is 0 |
End | Optional. Where to end the search. Default is to the end of the string |
Example: To find the first occurrence of the letter “e” in txt:
txt = “Hello, welcome to my world.”
x = txt.find(“e”)
print(x)
Output: 1
Example 2: Where in the text is the first occurrence of the letter “e” when you only search between position 5 and 10?:
txt = “Hello,welcome to my world.”
x = txt.find(“e”, 5, 10)
print(x)
Output: 8
3-rfind(): The rfind() searches the string for a specified value and returns the last position of where it was found.
Example:
- The rfind() method finds the last occurrence of the specified value.
- The rfind() method returns -1 if the value is not found.
Syntax: string.rfind(value, start, end)
Example: Where in the text is the last occurrence of the string “nielit”?:
txt = “nielit has started o level course nielit”
x = txt.rfind(“nielit”)
print(x)
Output: 43
Example: Where in the text is the last occurrence of the letter “e” when you only search between position 5 and 10?:
txt = “Hello, welcome to NIELIT”
x = txt.rfind(“e”, 5, 10)
print(x)
Output: 8
Example: If the value is not found, the rfind() method returns -1
txt = “Hello, welcome to NIELIT”
x = txt.rfind(‘nielit’)
print(x)
Output: -1
String Functions Contd..
4-capitalize():
This method converts the first character to upper case. The capitalize() method returns a string where the first character is upper case.
Example: Upper case the first letter in this sentence:
txt = “hello, welcome to NIELIT”
x = txt.capitalize()
print (x)
Output: Hello, welcome to nielit.
5-title()
The title() method returns a string where the first character in every word is upper case. Like a header, or a title.
Example:
txt = “python programming using string”
x = txt.title()
print(x)
Output: Python Programming Using String
If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Example:
txt = ” 3rd generation python”
x = txt.title()
print(x)
Output: 3Rd Generation Python
Example: Note that the first letter after a non-alphabet letter is converted into a upper case letter:
txt = “hello b2b2b2 and 3g3g3g”
x = txt.title()
print(x)
Output: Hello B2B2B2 And 3G3G3G
6-lower()
The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
Example: txt = “Welcome To NIELIT”
x = txt.lower()
print(x)
Output: welcome to nielit
7-upper()
The upper() method returns a string where all characters are in upper case. Symbols and Numbers are ignored.
Example: txt = “Welcome To NIELIT”
x = txt.upper()
print(x)
Output: WELCOME TO NIELIT
8-islower()
The islower() method returns True if all the characters are in lower case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.
Example: txt = “hello world!”
x = txt.islower()
print(x)
Output: True
9-isupper()
The isupper() method returns True if all the characters are in upper case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.
Example: txt = “PYTHON PROGRAM”
x = txt.isupper()
print(x)
Output: True
10-istitle()
The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False. Symbols and numbers are ignored.
Example:
a = “HELLO, AND WELCOME TO MY WORLD”
b = “Hello”
c = “22 Names”
d = “This Is %’!?”
print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())
Output:
False
True
True
True
11-replace()
The replace() method replaces a specified phrase with another specified phrase.
Syntax: string.replace(oldvalue, newvalue, count)
Parameter Values
Parameter | Description |
oldvalue | Required. The string to search for |
newvalue | Required. The string to replace the old value with |
count | Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences |
Example: Replace all occurrence of the word “one”:
txt = “one one was a race horse, two two was one too.”
x = txt.replace(“one”, “three”)
print(x)
Output: three three was a race horse, two two was three too.
Example: Replace the two first occurrence of the word “one”:
txt = “one one was a race horse, two two was one too.”
x = txt.replace(“one”, “three”, 2)
print(x)
Output: three three was a race horse, two two was one too.
12-strip()
The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)
Syntax string.strip(characters)
Parameter Values
Parameter | Description |
characters | Optional. A set of characters to remove as leading/trailing characters |
Example: Remove spaces at the beginning and at the end of the string:
txt = ” banana “
x = txt.strip()
print(x)
Output: banana
Example: Remove the leading and trailing characters other than space
txt = “,,,,,rrttgg…..apple….rrr”
x = txt.strip(“,.grt”)
print(x)
Output: apple
String Functions Contd..
lstrip()
The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax : string.lstrip(characters)
Where, character is Optional. A set of characters to remove as leading characters
Example: txt = “,,,,,ssaaww…..banana.. “
x = txt.lstrip(“,.asw”)
print(x)
Output: banana..
Note: Only leading character on left side will be removed.
rstrip()
The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
Syntax: string.rstrip(characters)
Where, characters is optional. A set of characters to remove as trailing characters
Example: txt = “banana,,,,,ssaaww…..”
x = txt.rstrip(“,.asw”)
print(x)
Output: banana..
Note: Only leading character on right side will be removed.
split():
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
Syntax string.split(separator, maxsplit)
Parameter | Description |
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is “all occurrences” |
Example: txt = “hello, my name is Peter, I am 26 years old”
x = txt.split(“, “)
print(x)
Output: [‘hello’, ‘my name is Peter’, ‘I am 26 years old’]
partition()
The partition() method searches for a specified string, and splits the string into a tuple containing three elements.
- The first element contains the part before the specified string.
- The second element contains the specified string.
- The third element contains the part after the string.
Syntax string.partition(value)
Where, value is required. The value is the string to search for
Example txt = “I could eat bananas all day”
x = txt.partition(“bananas”)
print(x)
Output: (‘I could eat ‘, ‘bananas’, ‘ all day’)
Search for the word “bananas”, and return a tuple with three elements:
1 – everything before the “banana”
2 – the “banana”
3 – everything after the “banana”
join()
The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
Example: join all items in a dictionary into a string, using a the word “and” as separator:
List1 =(“apple”,”Bannana”)
mySeparator = ” and “
x = mySeparator.join(List1)
print(x)
Output: apple and Bannana
isspace()
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Example: txt = ” s “
x = txt.isspace()
print(x)
Output: False