Python – Variables

Python Variables

Python is not a “statically typed” language. We do not need to declare variables or their types before using them. When we first assign a value to a variable, it is generated. A variable is a name that is assigned to a memory location. It is the fundamental storage unit in a program.

In this post, we’ll go over what you need to know about variables in Python.

Variables in Python Language

1)Variable

Variables are simply reserved memory locations for storing values. This means that when you construct a variable, you reserve memory space.

The interpreter allocates memory and specifies what can be stored in reserved memory based on the data type of a variable. As a result, you can store integers, decimals, or characters in variables by assigning various data types to them.

2)Important points about variables

  • In Python we don’t have to give the type of information when defining a variable, unlike the other programming languages (C++ or Java). The variable form is assumed by Python implicitly on the basis of a variable value.
  • During program execution, the value stored in a variable may be modified.
  • A variable is simply the name given to a memory location, all operations performed on the variable have an impact on that memory location.

3)Initializing the value of the variable

There is no clear statement to reserve the memory space for Python variables. When you assign a value to a variable, the declaration occurs automatically. To allocate values to the variables, the same sign (=) is used.

The = operator’s left operand is the variable name and the operand’s right is the value in the variable. The = operator is the variable value.

Examples:

A=100
b="Hello"
c=4.5

4)Memory and reference

A variable in Python resembles a tag or a reference that points to a memory object.

As an example,

k=”BTechGeeks”

‘BTechGeeks’ is an string object in the memory, and k is a reference or tag the indicates that memory object.

5)Modifying the variable value

Let us try this:

p=4.5
p="Cirus"

Initially, p pointed to a float object, but now it points to a string object in memory. The variable’s type also changed; originally, it was a decimal (float), but when we assigned a string object to it, the type of p changed to str, i.e., a string.

If there is an object in memory but no vector pointing to it, the garbage collector can automatically free it. We forced the variable p to point to a string object, as in the preceding example, and then float 4.5 was left in memory with no variable pointing to it. The object was then immediately released by the garbage collector.

6)Assigning one variable with another variable

We can assign the value of one variable with another variable like

p="BtechGeeks"
q=p

Both the p and q variables now point to the same string object, namely, ‘BTechGeeks.’

Below is the implementation:

p = "BTechGeeks"
# assign variable q with p
q = p
# print the values
print("The value of p :", p)
print("The value of q :", q)

Output:

The value of p : BTechGeeks
The value of q : BTechGeeks

7)The following are the rules for creating variables in Python

  • A variable name must begin with a letter or an underscore.
  • A number cannot be the first character in a variable name.
  • Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _ ).
  • Case matters when it comes to variable names (flag, Flag and FLAG Aare three different variables).
  • The reserved terms (keywords) are not permitted to be used in naming the variable.

Related Programs:

Compare and get Differences between two Lists in Python

Compare and get Differences between two Lists in Python

Lists in Python:

Lists are the most versatile ordered list object type in Python. It’s also known as a sequence, which is an ordered group of objects that can contain objects of any data form, including Python Numbers, Python Strings, and nested lists. One of the most widely used and flexible Python Data Types is the list.

You can check if two lists are equal python.

Examples:

Input:

list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

Output:

Printing the Differences between the lists : 
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

Compare and get Differences between two Lists in Python

Let’s say we have two lists

There may be certain items in the first list that are not present in the second list. There are also several items that are present in the second list but not in the first list. We’d like to compare our two lists to figure out what the variations are.

There are several ways to compare and get differences between two lists some of them are:

Method #1:Using union function in sets

When we make a set from a list, it only includes the list’s unique elements. So, let’s transform our lists into sets, and then subtract these sets to find the differences.
We discovered the variations between the two lists, i.e. elements that are present in one list but not in the other.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]
# converting two lists to sets
setlist1 = set(list1)
setlist2 = set(list2)
# getting the differences in both lists
listDif = (setlist1 - setlist2).union(setlist2 - setlist2)
print('Printing the Differences between the lists : ')
print(listDif)

Output:

Printing the Differences between the lists : 
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

Method #2:Using set.difference()

Instead of subtracting two sets with the – operator in the previous solution, we can get the differences by using the set difference() feature.

So, let’s convert our lists to sets, and then use the difference() function to find the differences between two lists.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]
# converting two lists to sets
setlist1 = set(list1)
setlist2 = set(list2)
# getting elements in first list which are not in second list
difference1 = setlist1.difference(setlist2)
# getting elements in second list which are not in first list
difference2 = setlist2.difference(setlist1)
listDif = difference1.union(difference2)
print('Printing the Differences between the lists : ')
print(listDif)

Output:

Printing the Differences between the lists : 
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

Method #3:Using List Comprehension

To find the differences, we can iterate over both lists and search for elements in other lists. However, we can use list comprehension for iteration.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

# getting elements in first list which are not in second list
difference1 = [element for element in list1 if element not in list2]
# getting elements in second list which are not in first list
difference2 = [element for element in list2 if element not in list1]
listDif = difference1+difference2
print('Printing the Differences between the lists : ')
print(listDif)

Output:

Printing the Differences between the lists : 
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

Method #4:Using set.symmetric_difference()

We had all of the variations between two lists in two steps in all of the previous solutions. Using symmetric difference(), however, we can accomplish this in a single stage.
Set has a member function called symmetric difference() that takes another sequence as an argument. It returns a new set containing elements from either the calling set object or the sequence statement, but not both. In other words, it returns the differences between set and list. Let’s see if we can use this to determine the differences between two lists.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

listDif = set(list1).symmetric_difference(list2)
print('Printing the Differences between the lists : ')
print(listDif)

Output:

Printing the Differences between the lists : 
{'is', 'online', 'world', 'BTechGeeks', 'Python', 'Language', 'Coding', 'Geeks', 'Platform'}

Method #5:Using set and ^ operator

Quick approach for solving this problem is to use ^ and sets.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

listDif = set(list1) ^ set(list2)
print('Printing the Differences between the lists : ')
print(listDif)

Output:

Printing the Differences between the lists : 
{'is', 'online', 'world', 'BTechGeeks', 'Python', 'Language', 'Coding', 'Geeks', 'Platform'}

Python How to Check if a Key Exists in Dictionary

How to Check if a Key Exists in Dictionary

A Python dictionary is a list of objects that are not in any particular order i.e Unordered.

A dictionary is made up of a collection of key-value pairs. Each key-value pair corresponds to a specific value.

Curly braces { } can be used to describe a dictionary by enclosing a comma-separated list of key-value pairs.

Every key is separated from its associated value by a colon “:”.

Given a dictionary, the task is to determine whether the given key exists in the dictionary.

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'python':300} , key = is

Output:

Yes

Check whether given Key already exists in a Python Dictionary

There are several ways to check whether the given key exists in the dictionary some of them are:

Method #1: Using keys() function

The keys() method returns a list of all the available keys in the dictionary. Using the inbuilt method keys(), use an if statement and the ‘in’ operator to determine whether or not the key exists in the dictionary.

# Given Dictionary

dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'

# Checking if key is exist in dictionary using keys() method
if key in dictionary.keys():
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #2: Using if-in Statements

To verify if a key exists in the dictionary, we can use the ‘in operator’ directly with the dictionary.

The expression:

key in dictionary

If the key exists in the dictionary, it will evaluate to True; otherwise, it will evaluate to False.

Let’s use this to see if the key is in the dictionary.

# Given Dictionary

dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'

# Using if and in to check whether the key is present in dictionary
if key in dictionary:
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #3: Using List and if statement

  • Convert the dictionary keys to list.
  • Check if the key present in this list using if statement.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Converting dictionary keys to list
keyslist = list(dictionary.keys())

# Checking if key is exist in list using if
if key in keyslist:
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #4: Using Exceptional Handling

It will raise a KeyError if we try to access a value of key that does not exist in the dictionary. This can also be used to see if anything exists in the dict.

This can also be a way to check if exist in dictionary or not .

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using try and except
try:
    # If the key exist in dictionary its value is assigned to test and then it prints yes
    test = dictionary[key]
    print("Yes")
# If the key do not exist in dictionary it prints no
except KeyError:
    print("No")

Output:

Yes

Method #5: Using get() function

The dict class in Python has a get() method that accepts a key and a default value.

dictionary.get(keyname, value)

The function’s behaviour,

  • If the given key is found in the dictionary, it returns the value associated with that key.
  • If the given key does not exist in the dictionary, the passed default value argument is returned.
  • If the given key does not exist in the dictionary and the default value is not provided, it returns None.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using get()
if dictionary.get(key) is not None:
    print("Yes")
else:
    print("No")

Output:

Yes

Method #6 : Using ‘if not in’ statement

We’ve just verified whether the key exists in the dictionary so far.

However, if we want to verify if a key does not exist in the dictionary, we can use ‘if not in’ with the dictionary directly.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using if not in
if key not in dictionary:
  # if the key not in dictionary then we print no
    print("No")
else:
    print("Yes")

Output:

Yes

Related Programs:

Python : How to Create a List and Initialize with Same Values

How to Create a List and Initialize with Same Values

In Python Data Structures, a list is a type of container that is used to store multiple pieces of data at the same time. In Python, unlike Sets, the list is ordered and has a definite count. A list’s elements are indexed in a specific order, and the indexing of a list begins with 0 as the first index.

This article will go over various methods to create a list and Initialize with same values.

Examples:

Input:

size=5 , value="BTechGeeks"

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Make a list and fill it with the same values

There are several ways create a list and initialize with same values some of them are:

Method #1:Using [] and multiply operator

Assume we want to make a list of strings that contains 5 identical strings, such as ‘BTechGeeks’.

You can do the following to initialize a list of immutable items, such as None, strings, tuples, or frozensets, with the same value:

# Function which converts list to string
def createList(size, value):
    # Using multiply operator
    requiredlist = [value]*size
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

[‘BTechGeeks’] will generate a list with a single value, which we can then multiply by 5. It will loop through the contents of the list 5 times.

Note: Never use [e]*n for mutable items. As a result, the list will contain the same object e repeated N times, as well as referencing errors.

Method #2:Using List Comprehension and range()

List comprehension is a simple and compact syntax for creating a list from a string or another list in Python. It’s a quick way to make a new list by performing an operation on each item in the existing one. List comprehension is much faster than using the for loop to process a list.

The for loop in this list comprehension will iterate over the range object 5 times, adding ‘BTechGeeks’ to the list with each iteration.

Below is the implementation:

# Function which converts list to string
def createList(size, value):
    # Using list comprehension and range
    requiredlist = [value for i in range(size)]
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Method #3: Using itertools repeat() function

The itertools package contains a repeat() function that creates an iterator that returns the object repeatedly. This has the same issue as [e]*n and should be avoided when dealing with mutable items.

Below is the implementation:

#importing itertools
import itertools

# Function which converts list to string
def createList(size, value):
    # Using repeat()
    requiredlist = list(itertools.repeat(value, size))
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Related Programs:

Python Convert String to Float

Convert String to Float Convert String to Float

In Python, strings are byte sequences that represent Unicode characters. Due to the lack of a character data type in Python, a single character is just a one-length string. To access the string’s components, use square brackets. To generate strings in Python, single quotes, double quotes, and even triple quotes can be used.

This article will go over various methods to convert string to float.

Example:

Input:

'34.124'

Output:

34.124

String to Float Conversion

We’ll look at how to convert a number string to a float object .

Form conversion functions in Python are used to transform one data type to another. The aim of this article is to provide details on how to convert a string to a float. To convert a String to a float in Python, use the float() function.

Float()

Any data form can be converted to a floating-point number using this function.

Syntax:

float(object)

Only one parameter is accepted by the process, and it is also optional to use. The method returns 0.0 if no argument is transmitted.

Parameters:

  • An int, float, or string may be used.
  • If it’s a string, it has to be in the right decimal format.

Return:

  • It gives you a float object as a result.
  • ValueError will be raised if the given string contains something other than a floating-point representation of a number.
  • If no argument is given, 0.0 is returned.
  • Overflow Error is raised if the given statement is beyond the range of float.

Let’s look at some examples of how to convert a string to a float object using the float() function.

Assume we have a Str object with the string ‘34.124′. We’ll transfer the string to the float() function to convert it to a floating-point number, or float entity. Which returns the float object after converting this string to a float. As an example,

# Driver code

# given string value
stringval = '34.124'

# converting string to float
floatvalue = float(stringval)

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34.124
Type of the number/object : <class 'float'>

Convert a comma-separated number string to a float object

Let’s say we have a string called ‘34,123.454’  which includes the number but also some commas. It’s a little difficult to convert this type of string to float. If we transfer this to the float() function directly, we’ll get an error as below:

ValueError: could not convert string to float: '34,123.454'

float() returned an error since string contained characters other than digits. So, before passing the string to the float() function, we need to delete all the extra commas.

We use replace function to replace commas with blank character such that commas  are deleted

Below is the implementation:

# Driver code

# given string value
stringval = '34,123.454'

# convert string with comma to float
# replacing ,(comma) with blank value
floatvalue = float(stringval.replace(',', ''))

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34123.454
Type of the number/object : <class 'float'>

Related Programs:

Python Check If there are Duplicates in a List

Check If there are Duplicates in a List

Lists are similar to dynamically sized arrays (e.g., vector in C++ and ArrayList in Java) that are declared in other languages. Lists don’t always have to be homogeneous, which makes them a useful tool in Python. Integers, Strings, and Objects are all DataTypes that can be combined into a single list. Lists are mutable, meaning they can be modified after they’ve been formed.

Duplicates are integers, strings, or items in a list that are repeated more than once.

Given a list, the task is to check whether it has any duplicate element in it.

Examples:

Input:

givenlist=["hello", "this", "is", "BTechGeeks" , "hello"]

Output:

True

Explanation:

hello is repeated twice so the answer is Yes

Check whether list contains any repeated values

There are several ways to check duplicate elements some of them are:

Method #1 :Using list and count() function

The list class in Python has a method count() that returns the frequency count of a given list element.

list.count(Element)

It returns the number of times an element appears in the list.

Approach:

The idea is to iterate over all of the list’s elements and count the number of times each element appears.

If the count is greater than one, this element has duplicate entries.

Below is the implementation:

# function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # Traverse the list
    for element in givenlist:
        # checking the count/frequency of each element
        if(givenlist.count(element) > 1):
            return True
    # if the above loop do not return anuthing then there are no duplicates
    return False

#Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n^2)

Method #2 : Using set()

Follow the steps below to see if a list contains any duplicate elements.

If the list does not contain any unhashable objects, such as list, use set().

When a list is passed to set(), the function returns set, which ignores duplicate values and keeps only unique values as elements..

Using the built-in function len(), calculate the number of elements in this set and the original list and compare them.

If the number of elements is the same, there are no duplicate elements in the original list ,if the number of elements is different, there are duplicate elements in the original list.

The following is the function that returns False if there are no duplicate elements and True if there are duplicate elements:

# function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # convert given list to set
    setlist = set(givenlist)
    # calculate length of set and list
    setlength = len(setlist)
    listlength = len(givenlist)
    # return the comparision between set length and list length
    return setlength != listlength


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n(log(n))

Method #3: Using Counter() function from collections (Hashing)

Calculate the frequencies of all elements using Counter() function which will be stored as frequency dictionary.

If the length of frequency dictionary is equal to length of list then it has no duplicates.

Below is the implementation:

# importing Counter function from collections
from collections import Counter

# function which return true if duplicates are present in list else false


def checkDuplicates(givenlist):
    # Calculating frequency using counter() function
    frequency = Counter(givenlist)
    # compare these two lengths and return it
    return len(frequency) != len(givenlist)


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n)
Related Programs:

Related Programs:

Python : How to Replace Single or Multiple Characters in a String ?

How to Replace Single or Multiple Characters in a String

A string is a series of characters.

A character is nothing more than a representation of something. For example, the English language has 26 characters.
Computers do not work with characters, but rather with numbers (binary). Despite the fact that you see characters on your screen, they are internally stored and manipulated as a series of 0s and 1s.
Encoding is the process of converting a character to a number, and decoding is the reverse process. ASCII and Unicode are two of the most common encodings.
In Python, a string is a sequence of Unicode characters.. Unicode was created to include every character in all languages and to bring encoding uniformity. Python Unicode can teach you everything you need to know about Unicode.

Examples:

Input:

string="Hello this is BTechGeeks" oldstring='e' replacestring='q'

Output:

Hqllo this is BTqchGqqks

Replace Single or Multiple Characters in a String

There are several ways to replace single or multiple characters in a String of them are:

Python has a string.replace() function

Syntax:

string.replace(old, new , count)

It returns a new string object that is a copy of the existing string with the content replaced. In addition, if count is not provided, it will return a string with all occurrences of ‘old’ replaced with ‘new’ string.
If the count parameter is supplied, it will return a string with the first ‘count’ occurrences of the ‘old’ string replaced with the ‘new’ string.

Replace all instances of a character or string in a string:

Assume we have a string, and now replace all occurrences of ‘e’ with ‘q’.

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'q'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hqllo this is BTqchGqqks

Because strings are immutable in Python, we can’t change their contents. As a result, member functions such as replace() produce a new string.

Replace the first n occurrences of a given character / substring in a string with another character / substring.

Suppose we want to replace character ‘e’ with ‘q000’ for first 2 i.e n occurrences then,

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    # providing count =2
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'q000'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hq000llo this is BTq000chGeeks

Replace multiple strings/characters in a string

The string.replace() function can only replace occurrences of a single substring.

But what if we need to replace multiple substrings within the same string?

To replace all occurrences of these three characters ‘e’, ‘h’, and ‘i’ with the string ‘##’ let us write a new function that extends replace().

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
  # Traverse the old string which needs to be replaced
    for element in oldstring:
        # Check if string is in the original string
        if element in string:
            # Replace the string eith replacestring
            string = string.replace(element, replacestring)

    # return the final string
    return string


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = ['e', 'i', 'h']
# replacing string/new string
replacestring = '##'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

H##llo t####s ##s BT##c##G####ks

Related Programs:

Python : How to access characters in string by index ?

How to access characters in string by index

A string is a collection of characters.

A character is simply a representation of something. The English language, for example, has 26 characters.
Computers work with numbers rather than characters (binary). Despite the fact that you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.
The process of converting a character to a number is known as encoding, and the process of converting a number to a character is known as decoding. Two of the most common encodings are ASCII and Unicode.
A string in Python is a sequence of Unicode characters. Unicode was created in order to include every character in every language and to bring encoding uniformity. Python Unicode is capable of teaching you everything you need to know about Unicode.

Examples:

Input:

string="Hello this is BTechGeeks" index=3

Output:

l

Retrieve characters in string by index

In this article, we will look at how to access characters in a string using an index.

>1)Accessing characters in a string by index | indexof

Python uses a zero-based indexing system for strings: the first character has index 0, the next has index 1, and so on.

The length of the string – 1 will be the index of the last character.

Suppose we want to access 3rd index in input string

We can implement it as:

# Given string
string = "Hello this is BtechGeeks"
# Given index
index = 3
character = string[index]
# printing the character at given index
print(character)

Output:

l

>2)Using a negative index to access string elements

Negative numbers may be used to specify string indices, in which case indexing is performed from the beginning of the string backward:

The last character is represented by string[-1]

The second-to-last character by string[-2], and so on.

If the length of the string is n, string[-n] returns the first character of the string.

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index from end
index = 3
# printing last two characters of string
print("Last character in the given string : ", string[-1])
print("Second Last character in given string : ", string[-2])
# printing n th character from end
print(str(index)+" character from end in given string :", string[-index])

Output:

Last character in the given string :  s
Second Last character in given string :  k
3 character from end in given string : e

>3)Using String Slicing :

# Given string
string = "Hello this is BtechGeeks"
# given start index and end index
startindex = 14
endindex = 19
# using slicing
print(string[startindex:endindex])

Output:

Btech

>4)Accessing Out Of range character in given string using Exceptional Handling:

IndexError will be thrown if an element in a string is accessed that is outside of its range, i.e. greater than its length. As a result, we should always check the size of an element before accessing it by index, i.e.

To handle the error we use exceptional handling in python

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index
index = 50
# using try and except
try:
    # if the given index is less than string length then it will print
    print(string[index])
# if index is out of range then it will print out of range
except:
    print("Index out of range")

Output:

Index out of range

 

Related Programs:

Python: Remove Last Element from a List

Remove Last Element from a List

Lists are ordered sequences of objects that may contain a variety of different object types. Members of lists can also be duplicated. Lists in Python are similar to arrays in other programming languages.. However, there is one important distinction. Python lists can contain objects of different data types, while arrays can only contain elements of the same data type.

An index is a position in a list.

Given a list, the task is to remove last element from the given list.

Examples:

Input:

givenlist = ["Btech" , "Geeks" ,"is" ,"new" ,"online" ,"platform" ]

Output:

Btech Geeks is new online

Explanation:

platform is the last element in givenlist hence it is deleted.

Remove the final item from a list

There are several ways to remove the final item from the list some of them are:

Method #1:Using pop() function

The list class in Python has a function called pop(index), which takes an optional argument index and deletes the element at that index. If no justification is given, it deletes the last element of the list by default.

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using pop() function
    givenlist.pop()
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

If the list is empty, the pop([i]) function throws an IndexError since it attempts to pop from an empty list.

Method #2:Using del keyword

The del statement is another way to delete an element from a list by using its index. It differs from the pop() function in that it does not return the element that has been removed. This does not generate a new list, unlike the slicing feature.

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using del keyword
    del givenlist[-1]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

If the list is empty, the above code raises an IndexError because it tries to reach an index of the list that is out of control.

Method #3: Using slicing

In Python, we know that lists can be cut. Slicing is a technique for removing the last element from a list. The aim is to create a sublist that contains all of the list’s elements except the last one. We must assign the new list to the original list since the slice operation returns a new list. The expression l = l[:-1], where l is your list, can be used to accomplish this. The abbreviation l[:-1] stands for l[0:len(l)-1].

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using slicing
    givenlist = givenlist[:-1]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

It should be noted that this function does not throw an error if the list is empty, but instead creates a copy of the list, which is not recommended.

Related Programs:

Python: Replace a Character in a String

Replace a Character in a String

A string is a character sequence.

A character is nothing more than a symbol. The English language, for example, has 26 characters.

Computers do not work with characters ,instead, they work with numbers (binary). Even though you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.

The process of converting a character to a number is known as encoding, and the reverse process is known as decoding. Some of the most common encodings are ASCII and Unicode.

In Python, a string is a sequence of Unicode characters.. Unicode was created in order to include every character in all languages and bring encoding uniformity. Python Unicode can teach you about Unicode.

This article will go over various methods to replace a character in a string

Examples:

Input:

string="BTechGeeks" oldstring='e' replacestring='p'

Output:

BTpchGppks

Modifying a Character in a String

There are several ways to replace a character in a string some of them are:

Method #1: Using replace() to replace all occurences

The Python string method replace() returns a copy of the string with old occurrences replaced with new, with the number of replacements optionally limited to max.

Syntax :

string .replace(old, new, count)

Parameters:

  • old−This is an old substring that needs to be replaced.
  • new − This is a new substring that will replace the old one.
  • max − Only the first count occurrences are replaced if the optional argument max is provided.

Return:
This method returns a string copy in which all occurrences of substring old are replaced with new. Only the first count occurrences are replaced if the optional argument max is provided.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace all occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring

# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The replace() method then returned a copy of the original string by replacing all occurrences of the character’s’ with the character ‘X’.

Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a copy of the string containing the replaced content.

Replace only first two occurences of string:

Instead of replacing all occurrences of a character in a string, we can use the count argument in the replace() function to replace only the first few occurrences of a character in a string.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace first 2 occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGpeks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The third argument was then passed as 2. The third argument is optional and tells the replace() function how many occurrences of the given sub-string should be replaced.

The replace() method then returned a copy of the original string by replacing only the first two occurrences of ‘e’ with the symbol ‘p.’
Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a duplicate of the string with the replaced content.

Method #2:Using for loop

Create an empty string and then iterate through all of the characters in the original string. Add each character to the new string during iteration. However, if a character needs to be replaced, use the replacement character instead.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
  # taking a empty string
    resultstring = ''
    # Traversee the originalstring
    for element in string:
      # if character is equal to old string then replace it
        if(element == oldstring):
            resultstring += replacestring
        else:
            resultstring += element

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

It replaced all instances of the character ‘e’ with the letter ‘p’

Because strings are immutable in Python, we cannot change their contents. As a result, we made a new copy of the string that contained the replaced content.

Method #3:Using Regex

Python includes a regex module (re), which includes a function sub() for replacing the contents of a string based on patterns. We can use the re.sub() function to replace/substitute all occurrences of a character in a string.

Below is the implementation:

import re

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # using regex
    resultstring = re.sub(oldstring, replacestring, string)

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

In this case, we used the sub() function with the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second argument. The third argument was then passed as the original string.

The Sub() function treated the first argument ‘s’ as a pattern and replaced all matches with the given replacement string, i.e ‘p’. As a result, it replaced all instances of the character ‘e’ with the character ‘p’ .Because strings are immutable in Python, we cannot change their contents. As a result, the regex module’s sub() function returns a copy of the string with the replaced content.
Related Programs: