Click for All Topics
In Python, a string is a sequence of characters. A character can be anything. it can be a letter or a number, a punctuation mark, or even a space. Strings represent text data – whether it’s a single word, a sentence, or even an entire book!
The computer does not understand characters it only knows about the combination of 0’s and 1’s (binary). It stores the character in binary.
In Python strings, each character is encoded into ASCII or Unicode character in computer so we can say that Python string is a collection of Unicode characters.
Example – creating strings in Python
string = 'edSlash' #string using single quote
string1 = "edSlash" #string using double quote
string2 = """Hello, Python this is edSlash
Official. """ #string using triple Quotes
s=str('Anurag Dubey')
print(string)
print(string1)
print(string2)
print(s)
# output -
# edSlash
# edSlash
# Hello, Python this is edSlash official.
# Anurag Dubey
In the above example, “edSlash” is a string. It contains seven characters – ‘e’, ‘d’, ‘S’, ‘l’, ‘a’, ‘s’, and ‘h’.
Str()
is an inbuilt function in python which is used to convert character into strings.Positive Indexing –
s='edSlash'
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
print(s[6])
print(s[7]) #it will gives an error index out of range
# Output-
# e
# d
# S
# l
# a
# s
# h
Negative Indexing –
s='edSlash'
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
print(s[-6])
print(s[-7])
# Output -
# h
# s
# a
# l
# S
# d
# e
Tips and Tricks – Only integer value is allowed to be used for indexing and slicing otherwise it will give
TypeError
.
While try to access an character with index out of range it will give an
IndexError
.
Syntax –
string[start:stop] # Start from first character to second last character
string[start:] # Start from first to end of the string string[:stop] # Start from the beginning till second last character string[:] # return whole string string[start:stop:step] # return start to stop, using step
Start
– it represents the first character index from where you want to start your substring and it is included in the result.
Stop
– it is the index of the last character upto you want to string and it is excluded in the result.
Step
– it represents the difference between each index by default its value is 1.
Example 1 –
string='Python'
print(string[::]) #Print whole string
print(string[::-1]) #Print reversed string
# Output
# Python
# nohtyP
Example 2 –
string='edSlash'
print(string[0:])
print(string[:7])
print(string[2:7])
print(string[0:7:2])
# output
# edSlash
# edSlash
# Slash
# eSah
Example 3 –
string='edSlash'
#Slicing using negative indexing
print('Negative Slicing\n')
print(string[::-1]) #reverse a string
print(string[-1:-5:-1])
print(string[-1:-7:-2])
# Output
# Negative Slicing
# hsalSde
# hsal
# haS
In the above example, we use negative slicing to extract a portion of a string.
Slice Method –
Syntax –
slice(start,stop,step)
Start
: The starting index of the slice is included in the slice object, by default its value is None.stop
: The last index of the slice is not included in the slice object, by default its value is None.step
: The step value for slicing, by default value, is 1.Example 1 –
s="Hello Python"
# Define slice
slice_string1=slice(0,5) #Extract Hello
slice_string2=slice(6,12,1) #Extract Python
print(s[slice_string1])
print(s[slice_string2])
# Output
# Hello
# Python
Example 2 – Passing slice as a function arguments
def get_substring(string, slicer):
return string[slicer]
s = "Python is general purpose programming language."
# Define a slice pattern using slice()
s_slice = slice(0, 6) # Extracts "Python"
# Use the function with the slice object
substring = get_substring(s, s_slice)
print(substring)
# Output
# Python
In the above example, we define a function called get_substring() that takes a string sequence and a slice object and returns a substring or a portion of the original string.
+
is a concatenation operator.Example –
# Example 1 -
s1='hello'
s2=' world!'
s=s1+s2
print(s)
# Output 1
# hello world!
# Example 2 -
name='anurag'
s="Good morning!"+" "+name
print(s)
# Output 2
# Good morning! anurag
*
) to achieve string repetitionExample –
# Example 1
string="Hello, "
repeated_string=string*2
print(repeated_string)
# Output 1
# Hello, Hello,
# Example 2
string1="Hello, "
repeated_string1=string1*0
print(repeated_string1) # Prints empty string
# Output 2
#
len()
function is used to find the length of a string.Example –
string='edSlash'
print(len(string))
# Output
# 7
==
operator is used for comparison of two strings.
# Example 1
s1="Hello! "
s2="World"
s=s1==s2
print(s)
# Output
# False
# Example 2
s1="edSlash"
s2="edSlash"
s=s1==s2
print(s)
# Output
# True
Example –
# Updating a character of a string
s="Hello"
print(s)
# change character at index 5
s=s[:4]+'n'
print(s)
# Output
# Hello #Before Updation string
# Helln #After Updation string
# Updating Entire string
s="Hello" #original string
print(s)
s="World!" #Updating string
print(s)
# Output
# Hello
# World!
del
keyword.del
keyword doesn’t delete the string it deletes the reference of the variable from the string and then the Python automatic garbage collector deletes the string from memory.Example –
# Delete one character from string.
string = "Hello Everyone"
print(string)
string=string[0:5]+string[6:]
print(string)
# Delete the space or we can say delete the character at index 6
# Output
# Hello Everyone
# HelloEveryone
# Delete the entire string
string ="Hello Everyone"
print(string)
del string
print(string) # This line gives an error
# Output
# Hello Everyone
# Traceback (most recent call last):
# File "/home/main.py", line 6, in
# print(string) # This line gives an error
#NameError: name 'string' is not defined
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India