String Manipulation and Type Conversion
Indexing (accessing characters in a string)
Strings can be indexed – often synonymously called subscripted as well.
Python supports both +ve index & -ve index
+ve index means left to right (forward direction) ---> forward indexing
-ve index means right to left (backward direction) ---> Reverse indexing
The first character of a string has the index 0.
Example
mystring = “Hello”
print(mystring[0])
output: H
Example
mystring = “Hello”
print(mystring[-1])
output: 0
Example
mystring = “Hello”
print(mystring[5])
output: string index out of range
Example
mystring = “Hello”
print(mystring[1.5])
output: string indices must be integers
slicing the strings
[start index (inclusive): end index (exclusive): step]
step can be either +ve or -ve & default value = +1
Example
mystring = “Hello”
mystring[2:5]
output:’llo’
Example
#slicing with increment
mystring = “Hello”
mystring[Link]-1]
output: ‘olle’
Example
#slicing with decrement
mystring = “Hello”
mystring[:4]
output: ‘Hell’
Example
#default start index = 0
mystring = “Hello”
mystring[:]
output: ‘Hello’
Example
#slicing (start to all)
mystring = “Hello”
mystring[::-1] #print in reverse order
output: ‘olleH’
String Methods
Python has a set of built-in reusable utilities.
They simplify the most commonly performed operations are:
String Methods
isdigit()
strip()
lower()
upper()
startswith()
endswith()
replace() and more...
Isdigit
Syntax: str_var.isdigit()
Gives True if all the characters are digits. Otherwise, False
Example:
is_digit = "98778".isdigit()
print(is_digit)
output:
True
Strip
Syntax: str_var.strip()
Removes all the leading and trailing spaces from a string.
Code:
mobile = " 9876543210 "
mobile = [Link]()
print(mobile)
output:
9876543210
Strip - Specific characters
Syntax: str_var.strip(chars)
We can also specify characters that need to be removed.
Code
name = "abcdef."
name = [Link](".")
print(name)
Output:
abcdef
Strip - Multiple Characters
Removes all spaces, comma(,) and full stop(.) that lead or trail the string.
Code
name = ", .. ,, ravi ,, .. ."
name = [Link](" ,.")
print(name)
Output:
ravi
Replace
Syntax: str_var.replace(old,new)
Gives a new string after replacing all the occurrences of the old substring with the new
substring.
Code
sentence = "teh cat and teh dog"
sentence = [Link]("teh","the")
print(sentence)
output:
the cat and the dog
Startswith
Syntax: str_var.startswith(value)
Gives True if the string starts with the specified value. Otherwise, False
Code
url = "[Link]
is_secure_url = [Link]("[Link]
print(is_secure_url)
Output:
True
Endswith
Syntax: str_var.endswith(value)
Gives True if the string ends with the specified value. Otherwise, False
Code
gmail_id = "python @[Link]"
is_gmail = gmail_id.endswith("@[Link]")
print(is_gmail)
output:
True
Upper
Syntax: str_var.upper()
Gives a new string by converting each character of the given string to uppercase.
Code
name = "abc"
print([Link]())
Output
ABC
Lower
Syntax: str_var.lower()
Gives a new string by converting each character of the given string to lowercase.
Code
name = "PYTHON"
print([Link]())
output:
python
Note: The upper() and lower() methods in Python work only on alphabetic characters and on
special characters (like punctuation marks, symbols, digits, etc.), these methods do not have
any effect.
Type Conversion
Converting the value of one data type to another data type is called Type Conversion or Type
Casting.
We can convert
String to Integer
Integer to Float
Float to String and so on.
String to Integer
int() converts valid data of any type to integer
Code
a = "5"
a = int(a)
print(type(a))
print(a)
output:
<class 'int'>
Invalid Integer Conversion
Code:
a = "Five"
a = int(a)
print(type(a))
Output:
ValueError:
invalid literal for int() with base 10: 'Five'
code:
a = "5.0"
a = int(a)
print(type(a)
output:
invalid literal for int() with base 10: '5.0'
Adding Two Numbers
a = input()
a = int(a)
b = input()
b = int(b)
result = a + b
print(result)
Input :
Output:
Integer to String
str() converts data of any type to a string.
a = input()
a = int(a)
b = input()
b = int(b)
result = a + b
print("Sum: " + str(result))
Input:
Output:
Sum: 7
Summary
int() -> Converts to integer data type
float() -> Converts to float data type
str() -> Converts to string data type
bool() -> Converts to boolean data type