Python

How to Replace Single or Multiple Characters in a String

Python : 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 Replace Single or Multiple Characters in a String ? Read More »

How to access characters in string by index

Python : 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 : How to access characters in string by index ? Read More »

Remove Last Element from a List

Python: 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: Remove Last Element from a List Read More »

Replace a Character in a String

Python: 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:

Python: Replace a Character in a String Read More »

Basics of Python – String Operations

In this Page, We are Providing Basics of Python – String Operations. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Operations

String operations

Some of the string operations supported by Python are discussed below.

Concatenation

Strings can be concatenated using + operator.

>>> word=' Python '+' Program '
>>> word
' Python Program '

Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions.

>>> ' Python ' ' Program '
' Python Program ' 
>>> word1=' Python '
>>> word2=' Program '
>>> word1 word2
File "<stdin>", line 1
word1 word2
                   ∧
SyntaxError: invalid syntax

Repetition

Strings can be repeated with the * operator.

>>> word=' Help '
>>> word * 3
' Help Help Help '
>>> 3 * word
' Help Help Help '

Membership operation

As discussed previously, membership operators in and not in are used to test for membership in a sequence.

>>> word=' Python '
>>> 'th' in word
True
>>> ' T ' not in word
True

Slicing operation

The string can be indexed, the first character of a string has sub-script (index) as 0. There is no separate character type; a character is simply a string of size one. A sub-string can be specified with the slice notation.

>>> word=' Python'
>>> word [2]
' t '
>>> word [0:2]
' Py '

String slicing can be in form of steps, the operation s [ i : j : k ] slices the string s from i to j with step k.

>>> word [1 :6 : 2]
' yhn '

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word [ : 2]
' Py '
>>> word [2 : ]
' thon '

As mentioned earlier, the string is immutable, however, creating a new string with the combined content is easy and efficient.

>>> word [0] = ' J '
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
TypeError : 'str' object does not support item assignment
>>> 'J ' + word[ 1 : ]
' Jython '

If the upper bound is greater than the length of the string, then it is replaced by the string size; an upper bound smaller than the lower bound returns an empty string.

>>> word [ 2 : 50 ]
'thon '
>>> word [ 4 : 1 ]
' '

Indices can be negative numbers, which indicates counting from the right-hand side.

>>> word [ -1 ]
' n '
>>> word [ -2 ]
' o '
>>> word [ -3 : ] 
' hon '
>>> word [ : -3 ]
' Pyt ' 
>>> word[-0]     # -0 is same as 0
' P '

Out-of-range negative slice indices are truncated, but a single element (non-slice) index raises the IndexError exception.

>>> word [ -100 : ]
' Python '
>>> word [ -100 ]
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
IndexError : string index out of range

String formatting

String objects have an interesting built-in operator called modulo operator (%). This is also known as the “string formatting” or “interpolation operator”. Given format%values (where a format is a string object), the % conversion specifications in format are replaced with zero or more elements of values. The % character marks the start of the conversion specifier.

If the format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (a dictionary). If the dictionary is provided, then the mapping key is provided in parenthesis.

>>> ' %s Python is a programming language. ' % ' Python '
' Python Python is a programming language. '
>>> ' %s Python is a programming language. ' % ( ' Python ' )
' Python Python is a programming language.'
>>>
>>> ' %s has %d quote types. ' % ( ' Python ' , 2 )
' Python has 2 quote types. '
>>> ' %s has %03d quote types. ' % ( ' Python ' , 2 )
' Python has 002 quote types. '  
>>> ' %( language )s has % ( number ) 03d quote types.' % \
. . . { " language " : " Python " , " number " : 2 }
' Python has 002 quote types. '

In the above example, 03 consists of two components:

  • 0 is a conversion flag i.e. the conversion will be zero-padded for numeric values.
  • 3 is minimum field width (optional).
ConversionMeaning
DSigned integer decimal.
1Signed integer decimal.
EFloating-point exponential format (lowercase).
EFloating-point exponential format (uppercase).
FFloating-point decimal format.
FFloating-point decimal format.
gFloating point format. Uses lowercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
GFloating point format. Uses uppercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
sString.

Precision (optional) is given as a dot (.) followed by the precision number. While using conversion type f, F, e, or E, the precision determines the number of digits after the decimal point, and it defaults to 6.

>>> " Today's stock price : %f " % 50
"Today's stock price: 50 000000"
>>> "Today's stock price : %F " % 50
"Today's stock price: 50 000000"
>>>
>>> "Today's stock price : %f " % 50.4625
"Today's stock price : 50 462500"
>>> "Today's stock price : %F " % 50.4625
"Today's stock price : 50 462500"
>>>
>>> "Today's stock price : %f " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>> "Today's stock price : %F " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>>
>>> "Today's stock price : %. 2f " % 50 . 4625
"Today's stock price : 50.46"
>>> "Today's stock price : %. 2F " % 50 . 4625
"Today's stock price : 50.46"
>>>
>>> "Today's stock price : %e " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : %E " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : % 3e " % 50 . 46251987624312359
"Today's stock price : 5 . 046e + 01 "
>>> "Today's stock price : % 3E " % 50 . 46251987624312359
"Today's stock price : 5 . 046E + 01 "

While using conversion type g or G, the precision determines the number of significant digits before and after the decimal point, and it defaults to 6.

>>> " Today's stock price : %g" % 50.46251987624312359
"Today's stock price: 50.4625"
>>> "Today's stock price: %G" % 50.46251987624312359
"Today's stock price: 50.4625"
>>>
>>> "Today's stock price: %g" % 0.0000005046251987624312359
"Today's stock price: 5.04625e-07"
»> "Today's stock price: %G" % 0.0000005046251987624312359
"Today's stock price: 5.04625E-07"

Python String Programs

Basics of Python – String Operations Read More »

Basics of Python – Regular Expression Module

In this Page, We are Providing Basics of Python – Regular Expression Module. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Regular Expression Module

Regular expression module

A regular expression (also called RE, or regex, or regex pattern) is a specialized approach in Python, using which programmers can specify rules for the set of possible strings that need to be matched; this set might contain English sentences, e-mail addresses, or anything. REs can also be used to modify a string or to split it apart in various ways.

Meta characters

Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. There are exceptions to this rule; some characters are special “meta characters”, and do not match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Some of the meta characters are discussed below:

Meta character

Description

Example

[ ]

Used to match a set of characters.

[time]

The regular expression would match any of the characters t, i, m, or e.

[a-z]

The regular expression would match only lowercase characters.

Used to complement a set of characters.[time]

The regular expression would match any other characters than t, i, m or e.

$

Used to match the end of string only.time$

The regular expression would match time in ontime, but will not match time in timetable.

*

Used to specify that the previous character can be matched zero or more times.tim*e

The regular expression would match strings like timme, tie and so on.

+

Used to specify that the previous character can be matched one or more times.tim+e

The regular expression would match strings like timme, timmme, time and so on.

?

Used to specify that the previous character can be matched either once or zero times.tim ?e

The regular expression would only match strings like time or tie.

{ }

The curly brackets accept two integer values. The first value specifies the minimum number of occurrences and the second value specifies the maximum of occurrences.tim{1,4}e

The regular expression would match only strings time, timme, timmme or timmmme.

Regular expression module functions

Some of the methods of re module as discussed below:

re. compile ( pattern )
The function compile a regular expression pattern into a regular expression object, which can be used for matching using its match ( ) and search ( ) methods, discussed below.

>>> import re
>>> p=re.compile ( ' tim*e ' )

re. match ( pattern, string )
If zero or more characters at the beginning of the string match the regular expression pattern, match-( ) return a corresponding match object instance. The function returns None if the string does not match the pattern.

re. group ( )
The function return the string matched by the RE.

>>> m=re .match ( ' tim*e' , ' timme pass time ' )
>>> m. group ( )
' timme '

The above patch of code can also be written as:

>>> p=re. compile ( ' tim*e ' )
>>> m=p.match ( ' timme pass timme ' )
>>> m.group ( )
'timme'

re. search ( pattern, string )
The function scans through string looking for a location where the regular expression pattern produces a match, and returns a corresponding match object instance. The function returns None if no position in the string matches the pattern.

>>> m=re.search( ' tim*e ' ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

re.start ( )
The function returns the starting position of the match.

re.end ( )
The function returns the end position of the match.

re.span ( )
The function returns a tuple containing the ( start, end ) indexes of the match.

>>> m=re.search ( ' tim*eno passtimmmeee ' )
>>> m.start ( )
7
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.start ( )
7 
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

re. findall ( pattern, string )
The function returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.findall ( ' tim*e ' , ' timeee break no pass timmmeee ' )
>>> m 
[ ' time ' , ' timmme ' ]

The above patch of code can also be written as:

>>> p=re . compile ( ' tim*e ' )
>>> m=p.findall ( ' timeee break no pass timmmeee ' )
>>> m
[ ' time ', ' timmme ' ]

re. finditer ( pattern, string )
The function returns an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in a string. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.finditer ( ' tim*e ', ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .           print match.group ( )
. . .           print match.span ( )
time 
( 0 , 4 ) 
timmme 
( 21 , 27 )

The above patch of code can also be written as:

>>> p=re.compile( ' tim*e ' )
>>> m=p.finditer ( ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .         print match.group ( )
. . .         print match.span ( )
time 
( 0 , 4 ) 
timmme
( 21 , 27 )

Basics of Python – Regular Expression Module Read More »

Basics of Python – String Methods

In this Page, We are Providing Basics of Python – String Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Methods

String methods

Below are listed some of the string methods which support both strings and Unicode objects. Alternatively, some of these string operations can also be accomplished using functions of the string module.

str.isalnum( )
Return True, if all characters in the string are alphanumeric, otherwise False is returned.

>>> str=" this2009 ”
>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False

str. isalpha ( )
Return True, if all characters in the string are alphabetic, otherwise False is returned.

>>> str=" this "
>>> str.isalpha ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalpha ( )
False

str.isdigit( )
Return True, if all characters in the string are digits, otherwise False is returned.

>>> str="this2009" 
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True

str . isspace ( )
Return True, if there are only whitespace characters in the string, otherwise False is returned.

>>> str= "    "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False

str.islower ( )
Return True, if all cased characters in the string are in lowercase and there is at least one cased character, false otherwise.

>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True
>>> str=" this2009 "
>>> str.islower ( )
True
>>> str=" 2009 "
>>> str.islower ( )
False

str.lower ( )
Return a string with all the cased characters converted to lowercase.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. lower (s), where s is a string.

>>> import string 
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! " 
>>> string:lower(str)
' this is String example. . . .wow ! ! ! '

str.isupper ( )
Return True, if all cased characters in the string are uppercase and there is at least one cased character, otherwise False is returned.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.isupper ( )
True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )
False

str.upper ( )
Return a string with all the cased characters converted to uppercase. Note that str . upper () . isupper () might be False, if string contains uncased characters.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '
>>> str.upper ( ) .isupper ( )
True
>>> str="@1234@"
>>> str.upper ( )
' @1234@ '
>>> str.upper ( ).isupper ( )
False

The above can be imitated using the string module’s function string. upper (s), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.upper (str)
' THIS IS STRING EXAMPLE. . . .WOW ! ! ! ’
>>> string.upper (str).isupper ( )
True 
>>> str="@1234@"
>>> string.upper(str)
'@1234@' 
>>> string.upper (str).isupper ( )
False

str.capitalize ( )
Return a string with its first character capitalized and the rest lowercase.

>>> str=" this Is stRing example. . . . wow ! ! ! "
>>> str.capitalize ( )
' This is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, capitalize (word), where the word is a string.

>>> str=" this Is stRing example. . . .wow ! ! ! "
>>> string.capitalize ( str )
' This is string example. . . .wow ! ! ! '

str.istitle ( )
Return True, if the string is title cased, otherwise False is returned.

>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.istitle ( )
False

str.title ( )
Return a title cased version of the string, where words start with an uppercase character and the remaining characters are lowercase. It will return unexpected results in cases where words have apostrophes etc.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! ! ! '
>>> str=" this isn't a float example. . . .wow ! ! ! "
>>> str.title ( )
" This Isn'T A Float Example. . . .Wow ! ! ! "

str.swapcase ( )
Return a copy of the string with reversed character case.

>>> str='' This is string example. . . .WOW ! ! ! "
>>> str . swapcase ( ) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. swap case (s), where s is a string.

>>> str=" This is string example. . . .WOW ! ! ! "
>>> string, swapcase (str) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

str.count(sub[,start[, end]])
Return the number of non-overlapping occurrences of sub-string sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> str.count (sub , 4 , 40)
2
>>> sub=" wow "
>>> str.count(sub)
1

The above can be imitated using string module’s function string. count (s, sub [, start [, end] ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> string.count( str , sub , 4 ,40 )
2
>>> sub=" wow "
>>> string.count( str,sub )
1

str.find(sub[,start[,end]])
Return the lowest index in the string where the sub-string sub is found, such that sub is contained in the slice s [ start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1, if the sub is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15 
>>> str1.find ( str2 , 40 )
-1

The above can be imitated using the string module’s function string. find (s, sub [, start [, end] ]), where s is a string.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam " 
>>> string.find ( str1 , str2 )
15 
>>> string.find(str1 , str2 , 10 )
15
>>> string.find( str1 , str2 , 40)
-1

The find ( ) method should be used only if there is a requirement to know the position of the sub. To check if the sub is a sub-string or not, use the in operator:

>>> ' Py ' in ' Python '
True

str.rfind(sub[,start[, end]] )
Return the highest index in the string where the sub-string sub is found, such that sub is contained within s [start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

>>> str1=" this is really a string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
>>> strl.rfind ( str2 , 10 , 20 )
-1

The above can be imitated using the string module’s function string.rfind(s, sub [, start [, end] ] ), where s is a string.

>>> str1=" this is really a string example. . . .wow ! ! ! " 
>>> str2=" is "
>>> string.rfind ( str1 , str2 )
5
>>> string.rfind ( str1 , str2 , 0 , 10 )
5
>>> string.rfind ( str1 , str2 , 10 , 0 )
-1

str.index ( sub [ , start [ , end ] ] )
Like find ( ), but raise ValueError when the sub-string is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 ) 
15 
>>> str1.index ( str2 , 10 )
15 
>>> str1.index ( str2 , 40 )
Traceback ( most recent call last ) :
File "<pyshell#38>", line 1, in <module>
str1 . index ( str2 , 40 ) 
ValueError: substring not found

The above can’ be imitated using string module’s function string, index (s, sub [, start [, end] ] ), where s is a string.

>>> str1 = " this is string example. . . .wow ! ! ! " 
>>> str2=" exam "
>>> string.index ( str1 , str2 )
15
>>> string. index ( str1 , str2 ,10 )
15
>>> string, index ( str1 , str2 , 40 )
Traceback ( most recent call last ) :
File " <stdin> ", line 1, in <module>
File " C : \ Python27 \ lib \ string.py ", line 328, in index 
return s . index ( *args )
ValueError: substring not found

str.rindex ( sub [ , start [ , end ] ] )
Like rfind ( ), but raises ValueError when the sub-string sub is not found.

>>> str1="this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rindex ( str1 , str2 )
5
>>> str1.rindex ( str2 , 10 , 20 )
Traceback (most recent call last) : 
File " <stdin> ", line 1, in <module>
ValueError: substring not found

The above can be imitated using the string module’s function string. rfind ( s, sub [, start [, end] ] ), where s is a string.

>>> str1= " this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> string.rindex ( str1 , str2 )
5
>>> string.rindex ( str1 , str2 , 10 , 20)
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
File." C : \ Python27 \ lib \ string.py" , line 337, in rindex 
return s.rindex ( *args )
ValueError: substring not found

str.startswith (prefix [ , start [ , end ] ] )
Return True, if string starts with the prefix, otherwise return False. The prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With an optional end, stop comparing string at that position.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.startswith( ' this ' )
True
>>> str.startswith( ' is ' , 2)
True
>>> str.startswith( ' this ' , 10 , 17 )
False
>>> pfx=( ' the ' , ' where ' , ' thi ' )
>>> str. startswith ( pfx )
True

str.endswith ( suffix [ , start [ , end ] ] )
Return True, if the string ends with the specified suffix, otherwise return False. The suffix can also be a tuple of suffixes to look for. The “est starts from the index mentioned by optional argument start. The comparison is stopped indicated by optional argument end.

>>> str=" this is string example. . . .wow ! ! ! "
>>> suffix=" wow ! ! ! "
>>> str.endswith ( suffix )
True
>>> suffix= ( " tot ! ! ! ", " wow ! ! ! " )
>>> str.endswith ( suffix )
True
>>> str.endswith ( suffix,20 )
True
>>> suffix= " is "
>>> str.endswith( suffix , 2 , 4 )
True
>>> str.endswith( suffix , 2 , 6 )
False
>>> str.endswith ( (' hey ’,' bye ',' w ! ! ! ' ) )
True

str. join ( iterable )
Return a string which is the concatenation of the strings in the iterable. The separator between elements is the string str providing this method.

>>> str="-" 
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq) 
' a-b-c '

The above can be imitated using the string module’s function string, join (words [, sep] ), where words is a list or tuple of strings, while the default value for sep is a single space character.

>>> str="-"
>>> seq= ( "a", "b", "c")
>>> string. join (seq, str)
'a-b-c'
>>> seq= [ ”a”, "b”, "c" ]
>>> string.join(seq,str) 
' a-b-c ’

str.replace ( old , new [ , count ] )
Return a string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

>>> str=" this is string example. . . . wow ! ! ! this is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was really string’
>>> str=" this is string example. . . .wow ! ! ! this is really string "
>>> str.replace (" is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string '

The above can be imitated using the string module’s function string. replace (s, old, new [, max replace ] ), where s is a string and may replace is the same as count (discussed above).

>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str, " is "," was " )
'thwas was string example. . . .wow ! ! ! thwas was really string'
>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str," is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string'

str.center ( width [ , fillchar ] )
Return centered string of length width. Padding is done using optional argument fillchar (default is a space).

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example. . . .wow ! ! ! "
>>> str.center (40)
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, center (s, width [, fillchar ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.center(str, 40 ,’ a ' )
'aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example .... wow!!!"
>>> string.center(str,40)
' this is string example. . . .wow ! ! ! '

str.1just ( width [ , fillchar ] )
Return the string left-justified in a string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow! ! ! " 
>>> str . 1 just (50, ' 0 ' )
'this is string example. . . .wow ! ! !000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1just (50)
' this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> str.1just (10)
' this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. 1 just (s, width [,fill char] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50, ' 0 ' )
' this is string example. . . .wow ! ! ! 000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50 )
'this is string example. . . .wow ! ! ! '

str.rjust ( width [ ,fillchar ] )
Return the right-justified string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! ! ! '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rjust ( 10 , ' 0 ' )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. rjust (s, width [, fillchar] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string .r just (str, 50, ’ 0 ’ )
' 000000000000000000this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> string.rjust (str , 10 , ' 0 ' ) .
' this is string example. . . .wow ! ! ! '

str.zfill ( width )
Return a string of length width, having leading zeros. The original string is returned, if the width is less than or equal to len(str).

>>> str=” this is string example. . . .wow ! ! ! "
>>> str.zfill (40)
'00000000this is string example. . . .wow ! ! ! ' 
>>> str . zf ill ( 45)
' 0000000000000this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, zfill (s, width), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string . zfill ( str , 40 ) 
'00000000this is string example. . . .wow ! ! ! ’
>>> string . zfill ( str , 45 ) 
' 0000000000000this is string example. . . .wow ! ! ! '

str.strip ( [ chars ] )
Return a string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. strip (s [, chars ] ), where s is a string.

>>> str=" 0000000this is string example. . . .wow ! ! ! 0000000"
>>> string, strip (str, ’ 0 ’ )
'this is string example. . . .wow ! ! ! '

str.1strip ( [ chars ] )
Return a string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1strip ( ) 
'this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.1strip ( ' 8 ' ) 
'this is string example. . . .wow ! ! ! 8888888 '

The above can be imitated using string module’s function string. lstrip (s [, chars] ), where s is a string.

>>> str="     this is string example. . . .wow ! ! !       "
>>> string.1strip (str)
' this is string example. . . .wow ! ! ! '
>>> str=" 888S8888this is string example. . . .wow ! ! ! 8888888 "
>>> string.1strip ( str , ' 8 ' )
' this is string example. . . .wow ! ! ! 8888888 '

str.rstrip ( [ chars ] )
Return a string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rstrip ( )
' this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.rstrip (' 8 ')
' 88888888this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string.rstrip (s [, chars] ), where s is a string.

>>> str="   this is string example. . . .wow ! ! ! "
>>> string.rstrip ( str )
' this is string example. . . .wow ! ! ! '
>>> str=  "88888888this is string example. . . .wow ! ! ! 8888888 "
>>> string.rstrip ( str,' 8 ' )
' 88888888this is string example. . . .wow ! ! ! '

str.partition(sep)
Split the string at the first occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="       this is string example. . . .wow ! ! !        "
>>> str.partition (' s ')
('        thi ' ,  ' s ' , ' is string example. . . .wow ! ! !       ' )

str.rpartition (sep)
Split the string at the last occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="         this is string example. . . .wow! ! !       "
>>> str.rpartition (' s ' )
(' this is ', ' s ', ' tring example. . . .wow ! ! ! ' )

str.split ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1 elements). If maxsplit is not specified or -1, then all possible splits are made. If sep is not specified or None, any whitespace string is a separator.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]
>>> str.split(' ',1)
[' Line1-abcdef ', '\nLine2-abc \nLine4-abcd ' ]

The above can be imitated using string module’s function string, split (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> string.split (str)
[ ' Line1-abcdef ', ' Line2-abc ', ' Line4-abcd ' ]
>>> string. split ( str,'   ',1 )
[ ' Line1-abcdef ', ' \nLine2-abc \nLine4-abcd ' ]

str.rsplit ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit () behaves like split () which is described in detail below.

>>> str="       this is string example. . . .wow ! ! !       "
>>> str.rsplit ( )
['this', 'is', 'string', 'example. . . .wow ! ! ! ' ]
>>> str.rsplit ( ' s ' )
['       thi ', ' i ', '   ', ' tring example. . . .wow ! ! ! ' ]

The above can be imitated using string module’s function string. rsplit (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="          this is string example. . . . wow ! ! !        "
>>> string. rsplit ( str )
[ ' this ' ,  ' is ' , ' string ' , ' example. . . .wow ! ! ! ' ]
>>> string. rsplit ( str , ' s ' )
['          thi' ; ' i ', ' ', 'tring example. . . .wow ! ! !                 ' ]

str. splitlines ( [ keepends ] )
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keeping is given.

>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "
>>> str.splitlines ( )
[ ' Line1-a b c d e f',   ' Line2- a b c ' , '   ' , ' Line4- a b c d ' ]
>>> str. splitlines (0)
[ ' Line1-a b c d e f ', ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.splitLines ( Fa1se )
[ ' Line1-a b c d e f ' , ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.sp1itLines (1)
[ ' Line1-a b c d e f\n ' , ' Line2- a b c\n', '\n', ' Line4- a b c d ' ]
>>> str.splitLines ( True )
[ ' Line1-a b c d e’ f\n', ' Line2- a b c\n', ' Line4- a b c d ' ]

str.translate ( table [ , deletechars ] )
Return a string having all characters occurring in the optional argument delete chars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

The maketrans ( ) function (discussed later in this section) from the string module is used to create a translation table. For string objects, set the table argument to None for translations that only delete characters.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' e ' , ' E ' )
>>> str.translate ( tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> str.translate ( tab , ' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> str.translate ( None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. translate (s, table [, deletechars ] ), where s is a string.

>>> str=’ this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans (' e ',' E ')
>>> string.translate ( str , tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , tab ,' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , None ,' ir ' )
' ths s stng example. . . .wow ! ! ! '

The following functions are there in the string module but are not available as string methods.

string.capwords(s[,sep])
Split the argument s into words using str. split (), then capitalize each word using str. capitalize ( ), and join the capitalized words using str. join ( ). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space, and leading and trailing whitespace is removed, otherwise, sep is used to split and join the words.

>>> str=" this is string example. . . .wow ! ! ! ''
>>> string.capwords (str)
' This Is String Example. . . .Wow ! ! ! '
>>> string.capwords (str, '    ' )
' This Is String Example. . . .Wow ! ! !    '
>>> string, capwords ( str,' s ' )
' this is sTring example. . . . wow ! ! ! ' 

string.maketrans ( from , to )
Return a translation table suitable for passing to translate (), that will map each character in from into the character at the same position in to, from and to must have the same length.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' t! ' , ' T. ' )
>>> string.translate ( str , tab )
'This is sTring example. . . .wow. . . '
>>> string.translate ( str , tab ,' ir ' )
' Ths s sTng example. . . .wow. . . '
>>> string.translate ( str , None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

Python String Programs

Basics of Python – String Methods Read More »

Basics of Python – String Constants

In this Page, We are Providing Basics of Python – String Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Constants

String constants

Some constants defined in the string module are as follows:

string. ascii_lowercase
It returns a string containing the lowercase letters ‘ abcdefghijklmnopqrstuvwxyz ‘.

>>> import string
>>> string . ascii_lowercase
' abcdefghijklmnopqrstuvwxyz '

string. ascii_uppercase
It returns a string containing uppercase letters ‘ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘.

>>> string . ascii_uppercase 
' ABCDEFGHIJKLMNOPQRSTUVWXYZ '

string. ascii_letters
It returns a string containing the concatenation of the ascii_lowercase and ascii_uppercase constants.

>>> string . ascii_letters
' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '

string. digits
It returns the string containing the digits ‘ 0123456789 ‘.

>>> string.digits 
' 0123456789 '

String.hex digits
It returns the string containing hexadecimal characters ‘ 0123456789abcdef ABCDEF ‘.

>>> string.hexdigits 
' 0123456789abcdef ABCDEF ’

string.octdigits
It returns the string containing octal characters ‘ 01234567 ‘.

>>> string.octdigits 
' 01234567 '

string. punctuation
It returns the string of ASCII characters which are considered punctuation characters.

>>> string.punctuation
‘ ! ” # $ % & \ ‘ ( ) * + , – . / : ; <=> ? @ [ \\ ] ∧ _ ‘ { | } ∼ ‘

string. whitespace
It returns the string containing all characters that are considered whitespace like space, tab, vertical tab, etc.

>>> string.whitespace
‘ \ t \ n \ x0b \ x0c \ r ‘

string. printable
It returns the string of characters that are considered printable. This is a combination of digits, letters, punctuation, and whitespace.

>>> string . printable
' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ! " # $ % & \ ' ( ) * + , - . / : ; <=> ? 0 [ \\ ]∧ _ ' { I \ t \ n \ r \ x0b \ x0c  '

Python String Programs

Basics of Python – String Constants Read More »

Dictionaries in Python

Python Dictionary:

Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.Keys are unique within a dictionary while values may not be.

Creating a dictionary:

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

Creating a dictionary

Output:

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

creating dictionary output
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

Using built-in function dict()

Output:

using built-in function dict() output

Nested Dictionary:

Using nested dictionary

Adding elements to a Dictionary:

In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary.While adding a value, if the key value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

Adding elements to a Dictionary

Output:

 

Accessing elements from a Dictionary:

In order to access the items of a dictionary refer to its key name.Key can be used inside square brackets.

Accessing elements from a Dictionary

Accessing element of a nested dictionary:

In order to access the value of any key in nested dictionary, use indexing []

Accessing element of a nested dictionary

Delete Dictionary Elements:

ou can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −

Delete Dictionary Elements

Properties of Dictionary Keys:

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.

(b)Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed.

Conclusion:

In this tutorial, you covered the basic properties of the Python dictionary and learned how to access and manipulate dictionary data.

Dictionaries in Python Read More »

How to Convert a Python String to int

Convert Python String to Int:

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

Below is the list of possible ways to convert an integer to string in python:

1. Using int() function:

Syntaxint(string)

Example:

Using int() function

Output:

Using int() function output
As a side note, to convert to float, we can use float() in python:

Example:

use float() in python

Output:

use float() in python output
2. Using float() function:

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer).

Syntax: float(string)

Example:

Using-float-function

Output:

Using float() function output

If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just follow the above method (pass the string to int()), which returns a decimal integer.But By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int(), then you’ll see a ValueError

For value error

The error message says that the string is not a valid decimal integer.

When you pass a string to int(), you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base:

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.

Conclusion:

This article is all about how to convert python string to int.All methods are clearly explained here. Now I hope you’re comfortable with the ins and outs of converting a Python string to an int.

How to Convert a Python String to int Read More »