Python

Strings in Python

Click for All Topics

Strings in Python

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’.

  • We can define string using single quote or double quote.
  • Triple Quote is used to define multi-line strings.
  • Str() is an inbuilt function in python which is used to convert character into strings.
  • It is an immutable data type in Python that means once you have created a string you cannot modify it.

Indexing in string-

  • In Python string, we can access an individual element of a string using indexing.
  • Square Brackets (’[]’) is used to access an element of a string.

Positive Indexing –

  • Accessing individual characters within a string using index values that begin at 0 and rise in value step by step is known as positive indexing in strings.
  • In positive indexing, the string’s initial character has an index of 0, the second character has an index of 1, and so on.
				
					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 –

  • Negative indexing is another way of accessing elements of a string using an index value.
  • In negative indexing, indexing starts from the last element of a string.
  • In negative indexing, the last element index is -1 the second last is -2, and so on in decreasing order.
  • It is very useful when you want to access an element from the end without knowing the length of the string.
				
					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 .

How to do slicing in Python string?

  • Slicing in a string means extracting a substring (slice or portion or a subsequence) from an original string.
  • It is the best way to work with a part of a string without modifying the original string.
  • Slicing is done using a range of indices.

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.

Stopit is the index of the last character upto you want to string and it is excluded in the result.

Stepit 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 –

  • It is an in-built function that returns a slice object which can then be used to extract a sequence of a string.
  • It is very useful when you have to reuse the same slice multiple times.
  • It is also useful when you need to pass slice parameters as an argument of a function.

Syntax –

slice(start,stop,step)

  • Parameters –
    • 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.

Operations on String –

Concatenation of String –

  • In Python, we can concatenate, join, or merge one string with another 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
				
			

String Multiplication or Repetition –

  • Repetition in the strings refers to creating a new string by repeating a given string a certain number of times.
  • we can use the multiplication operator(*) to achieve string repetition
  • It will give us a repeated string of the original string at the number of times we multiplied with an integer value.

Example –

				
					# 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
# 

				
			

Length of String –

  • We can find the length of a string or the total number of elements in a string
  • len() function is used to find the length of a string.

Example –

				
					string='edSlash'
print(len(string))

# Output 
# 7
				
			

Compare two strings-

  • In Python, we can also compare two strings whether they are equal or not.
  • == operator is used for comparison of two strings.
  • It will return True if both strings are the same else it will return False
				
					# 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
				
			

How to update a string in Python? –

  • As we know string is an immutable data type which means we can’t modify or update a string.
  • We can define a new string or reassign a string with an updated string of the original string.

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!
				
			

How to delete a string? –

  • As we know that string is immutable so we can not delete a character from a string.
  • We can delete a character using slicing in the string.
  • Also, we can delete the entire string using the 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 <module>
   # print(string) # This line gives an error 
#NameError: name 'string' is not defined