Let's focus on $tring Methods✌

 $tring Methods

        Python has set of built-in methods(methods that are already available inside python) that can be played over strings to view different output.

        Before playing with string methods it is necessary to know all the available methods.


        To list all string methods we can use method dir()

        The dir() function returns all properties and methods of the specified object, without the values.

        This function will return all the properties and methods, even built-in properties which are default for all object.

        syntax:   dir(datatype)   

        Example:     dir(str())        # list all methods available within string.

    
    
         
        

 

    
 
        The above listed methods are the built-in string methods. We can view 2 different types of methods been listed. Methods which starts and ends with  underscores(__) are known as special methods which executed by python itself.

        

Python String capitalize()

In Python, the capitalize() method converts first character of a string to uppercase letter and lower cases all other characters, if any.

The syntax of capitalize() is:

string.capitalize()

capitalize() Parameter

The capitalize()function doesn't take any parameter.


Return Value from capitalize()

The capitalize() function returns a string with the first letter capitalized and all other characters lower cased. It doesn't modify the original string.


Example: Capitalize a Sentence

string = "python Strings"

capitalized_string = string.capitalize()

print('Old String: ', string)
print('Capitalized String:', capitalized_string)

Output

Old String: python Strings
Capitalized String: Python strings

Python String center()

The center() method returns a string which is padded with the specified character.

The syntax of center() method is:

string.center(width[, fillchar])

center() Parameters

The center() method takes two arguments:

  • width - length of the string with padded characters
  • fillchar (optional) - padding character

The fillchar argument is optional. If it's not provided, space is taken as default argument.


Return Value from center()

The center() method returns a string padded with specified fillchar. It doesn't modify the original string.


Example 1: center() Method With Default fillchar

string = "Python STRINGS"

new_string = string.center(24)

print("Centered String: ", new_string)

Output

Centered String:     Python STRINGS    

Example 2: center() Method With * fillchar

string = "Python STRINGS"

new_string = string.center(24, '*')

print("Centered String: ", new_string)

Output

Centered String:  ***Python STRINGS****

Python String casefold()

The casefold() method is an aggressive lower() method which converts strings to case folded strings for caseless matching.

The casefold() method removes all case distinctions present in a string. It is used for caseless matching, i.e. ignores cases when comparing.

For example, the German lowercase letter ß is equivalent to ss. However, since ß is already lowercase, the lower() method does nothing to it. But, casefold() converts it to ss.

The syntax of casefold() is:

string.casefold()

Parameters for casefold()

The casefold() method doesn't take any parameters.


Return value from casefold()

The casefold() method returns the case folded string.


Example: Lowercase using casefold()

string = "PYTHON STRINGS"

# print lowercase string
print("Lowercase string:", string.casefold())

Output

Lowercase string: python strings

Python String count()

The string count() method returns the number of occurrences of a sub In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

The syntax of count() method is:

string.count(substring, start=..., end=...)

String count() Parameters

string in the given string.count() method only requires a single parameter for execution. However, it also has two optional parameters:

  • substring - string whose count is to be found.
  • start (Optional) - starting index within the string where search starts.
  • end (Optional) - ending index within the string where search ends.

Note: Index in Python starts from 0, not 1.


Return value from String count()

count() method returns the number of occurrences of the substring in the given string.


Example : Count number of occurrences of a given substring

# define string
string = "Python is an amazing language and it is using oops concept"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

Output

The count is: 2

Python String endswith()

The endswith() method returns True if a string ends with the specified suffix. If not, it returns False.The syntax of endswith() is:

str.endswith(suffix[, start[, end]])

endswith() Parameters

The endswith() takes three parameters:

  • suffix - String or tuple of suffixes to be checked
  • start (optional) - Beginning position where suffix is to be checked within the string.
  • end (optional) - Ending position where suffix is to be checked within the string.

Return Value from endswith()

The endswith() method returns a boolean.

  • It returns True if strings ends with the specified suffix.
  • It returns False if string doesn't end with the specified suffix.

Example 1: endswith() Without start and end Parameters

text = "Python is easy to learn."

result = text.endswith('to learn')
# returns False
print(result)

result = text.endswith('to learn.')
# returns True
print(result)

result = text.endswith('Python is easy to learn.')
# returns True
print(result)

Output

False
True
True

Example 2: endswith() With start and end Parameters

text = "Python programming is easy to learn."

# start parameter: 7
# "programming is easy to learn." string is searched
result = text.endswith('learn.', 7)
print(result)

# Both start and end is provided
# start: 7, end: 26
# "programming is easy" string is searched

result = text.endswith('is', 7, 26)
# Returns False
print(result)

result = text.endswith('easy', 7, 26)
# returns True
print(result)

Output

True
False
True

Python String expandtabs()

The expandtabs() method returns a copy of string with all tab characters '\t' replaced with whitespace characters until the next multiple of tabsize parameter.The syntax of expandtabs() method is:

string.expandtabs(tabsize)

expandtabs() Parameters

The expandtabs() takes an integer tabsize argument. The default tabsize is 8.


Return Value from expandtabs()

The expandtabs() returns a string where all '\t' characters are replaced with whitespace characters until the next multiple of tabsize parameter.


Example : expandtabs() With no Argument

str = 'xyz\t12345\tabc'

# no argument is passed
# default tabsize is 8
result = str.expandtabs()

print(result)

Output

xyz     12345   abc

Python String encode()

The string encode() method returns encoded version of the given string.Since Python 3.0, strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points.

For efficient storage of these strings, the sequence of code points is converted into a set of bytes. The process is known as encoding.

There are various encodings present which treats a string differently. The popular encodings being utf-8ascii, etc.

Using string's encode() method, you can convert unicoded strings into any encodings supported by Python. By default, Python uses utf-8 encoding.


The syntax of encode() method is:

string.encode(encoding='UTF-8',errors='strict')

String encode() Parameters

By default, encode() method doesn't require any parameters.

It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.

However, it takes two parameters:

  • encoding - the encoding type a string has to be encoded to
  • errors - response when encoding fails. There are six types of error response
    • strict - default response which raises a UnicodeDecodeError exception on failure
    • ignore - ignores the unencodable unicode from the result
    • replace - replaces the unencodable unicode to a question mark ?
    • xmlcharrefreplace - inserts XML character reference instead of unencodable unicode
    • backslashreplace - inserts a \uNNNN escape sequence instead of unencodable unicode
    • namereplace - inserts a \N{...} escape sequence instead of unencodable unicode

Example 1: Encode to Default Utf-8 Encoding

# unicode string
string = 'pythön!'

# print string
print('The string is:', string)

# default encoding to utf-8
string_utf = string.encode()

# print result
print('The encoded version is:', string_utf)

Output

The string is: pythön!
The encoded version is: b'pyth\xc3\xb6n!'

Example 2: Encoding with error parameter

# unicode string
string = 'pythön!'

# print string
print('The string is:', string)

# ignore error
print('The encoded version (with ignore) is:', string.encode("ascii", "ignore"))

# replace error
print('The encoded version (with replace) is:', string.encode("ascii", "replace"))

Output

The string is: pythön!
The encoded version (with ignore) is: b'pythn!'
The encoded version (with replace) is: b'pyth?n!'

Python String find()

The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.The syntax of the find() method is:

str.find(sub[, start[, end]] )

Parameters for the find() method

The find() method takes maximum of three parameters:

  • sub - It is the substring to be searched in the str string.
  • start and end (optional) - The range str[start:end] within which substring is searched.

Return Value from find() method

The find() method returns an integer value:

  • If the substring exists inside the string, it returns the index of the first occurence of the substring.
  • If substring doesn't exist inside the string, it returns -1.

Working of find() method

How find() and rfind() works in Python?
Working of Python string's find() and rfind() methods

Example 1: find() With No start and end Argument

quote = 'Let it be, let it be, let it be'

# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result)

# find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result)

# How to use find()
if (quote.find('be,') != -1):
    print("Contains substring 'be,'")
else:
    print("Doesn't contain substring")

Output

Substring 'let it': 11
Substring 'small ': -1
Contains substring 'be,'

Example 2: find() With start and end Arguments

quote = 'Do small things with great love'

# Substring is searched in 'hings with great love'
print(quote.find('small things', 10))

# Substring is searched in ' small things with great love' 
print(quote.find('small things', 2))

# Substring is searched in 'hings with great lov'
print(quote.find('o small ', 10, -1))

# Substring is searched in 'll things with'
print(quote.find('things ', 6, 20))

Output

-1
3
-1
9

Python String format()

The string format() method formats the given string into a nicer output in Python.

String format() Parameters

format() method takes any number of parameters. But, is divided into two types of parameters:

  • Positional parameters - list of parameters that can be accessed with index of parameter inside curly braces {index}
  • Keyword parameters - list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}

Return value from String format()

The format() method returns the formatted string.The format() method allows the use of simple placeholders for formatting.

Example : Basic formatting for default, positional and keyword arguments

# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))

# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))

# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))

# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))

Output

Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.

Python String index()

The index() method returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.The syntax of the index() method for string is:

str.index(sub[, start[, end]] )

index() Parameters

The index() method takes three parameters:

  • sub - substring to be searched in the string str.
  • start and end(optional) - substring is searched within str[start:end]

Return Value from index()

  • If substring exists inside the string, it returns the lowest index in the string where substring is found.
  • If substring doesn't exist inside the string, it raises a ValueError exception.

The index() method is similar to find() method for strings.

The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception.


Example 1: index() With Substring argument Only

sentence = 'Python programming is fun.'

result = sentence.index('is fun')
print("Substring 'is fun':", result)

result = sentence.index('Java')
print("Substring 'Java':", result)

Output

Substring 'is fun': 19

Python String isalnum()

The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.The syntax of isalnum() is:

string.isalnum()

isalnum() Parameters

The isalnum() doesn't take any parameters.


Return Value from isalnum()

The isalnum() returns:

  • True if all characters in the string are alphanumeric
  • False if at least one character is not alphanumeric

Example : Working of isalnum()

name = "M234onica"
print(name.isalnum())

# contains whitespace
name = "M3onica Gell22er "
print(name.isalnum())

name = "Mo3nicaGell22er"
print(name.isalnum())

name = "133"
print(name.isalnum())

Output

True
False
True
True

Python String isalpha()

The isalpha() method returns True if all characters in the string are alphabets. If not, it returns False.The syntax of isalpha() is:

string.isalpha()

isalpha() Parameters

isalpha() doesn't take any parameters.


Return Value from isalpha()

The isalpha() returns:

  • True if all characters in the string are alphabets (can be both lowercase and uppercase).
  • False if at least one character is not alphabet.

Example : Working of isalpha()

name = "Monica"
print(name.isalpha())

# contains whitespace
name = "Monica Geller"
print(name.isalpha())

# contains number
name = "Mo3nicaGell22er"
print(name.isalpha())

Output

True
False
False

Python String isdecimal()

The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.The syntax of isdecimal() is

string.isdecimal()

isdecimal() Parameters

The isdecimal() doesn't take any parameters.


Return Value from isdecimal()

The isdecimal() returns:

  • True if all characters in the string are decimal characters.
  • False if at least one character is not decimal character.

Example : Working of isdecimal()

s = "28212"
print(s.isdecimal())

# contains alphabets
s = "32ladk3"
print(s.isdecimal())

# contains alphabets and spaces
s = "Mo3 nicaG el l22er"
print(s.isdecimal())

Output

True
False
False

Python String isdigit()

The isdigit() method returns True if all characters in a string are digits. If not, it returns FalseThe syntax of isdigit() is

string.isdigit()

isdigit() Parameters

The isdigit() doesn't take any parameters.


Return Value from isdigit()

The isdigit() returns:

  • True if all characters in the string are digits.
  • False if at least one character is not a digit.

Example : Working of isdigit()

s = "28212"
print(s.isdigit())

# contains alphabets and spaces
s = "Mo3 nicaG el l22er"
print(s.isdigit())

Output

True
False

Python String isidentifier()

The isidentifier() method returns True if the string is a valid identifier in Python. If not, it returns False.The syntax of isidentifier() is:

string.isidentifier()

isidentifier() Paramters

The isidentifier() method doesn't take any parameters.


Return Value from isidentifier()

The isidentifier() method returns:

  • True if the string is a valid identifier
  • False if the string is not a invalid identifier

Example :  isidentifier() 

str = 'Python'
print(str.isidentifier())

str = 'Py thon'
print(str.isidentifier())

str = '22Python'
print(str.isidentifier())

str = ''
print(str.isidentifier())

Output

True
False
False
False

Python String islower()

The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.The syntax of islower() is:

string.islower()

islower() parameters

The islower() method doesn't take any parameters.


Return Value from islower()

The islower() method returns:

  • True if all alphabets that exist in the string are lowercase alphabets.
  • False if the string contains at least one uppercase alphabet.

Example : Return Value from islower()

s = 'this is good'
print(s.islower())

s = 'th!s is a1so g00d'
print(s.islower())

s = 'this is Not good'
print(s.islower())

Output

True
True
False

Python String isnumeric()

The isnumeric() method returns True if all characters in a string are numeric characters. If not, it returns False.The syntax of isnumeric() is

string.isnumeric()

isnumeric() Parameters

The isnumeric() method doesn't take any parameters.


Return Value from isnumeric()

The isnumeric() method returns:

  • True if all characters in the string are numeric characters.
  • False if at least one character is not a numeric character.

Example : Working of isnumeric()

s = '1242323'
print(s.isnumeric())

#s = '²3455'
s = '\u00B23455'
print(s.isnumeric())

# s = '½'
s = '\u00BD'
print(s.isnumeric())

s = '1242323'
s='python12'
print(s.isnumeric())

Output

True
True
True
False

Python String isprintable()

The isprintable() methods returns True if all characters in the string are printable or the string is empty. If not, it returns False.The syntax of isprintable() is:

string.isprintable()

isprintable() Parameters

isprintable() doesn't take any parameters.


Return Value from isprintable()

The isprintable() method returns:

  • True if the string is empty or all characters in the string are printable
  • False if the string contains at least one non-printable character

Example : Working of isprintable()

s = 'Space is a printable'
print(s)
print(s.isprintable())

s = '\nNew Line is printable'
print(s)
print(s.isprintable())

s = ''
print('\nEmpty string printable?', s.isprintable())

Output

Space is a printable
True

New Line is printable
False

Empty string printable? True

Python String isspace()

The isspace() method returns True if there are only whitespace characters in the string. If not, it return False.Characters that are used for spacing are called whitespace characters. For example: tabs, spaces, newline, etc.

The syntax of isspace() is:

string.isspace()

isspace() Parameters

isspace() method doesn't take any parameters.


Return Value from isspace()

isspace() method returns:

  • True if all characters in the string are whitespace characters
  • False if the string is empty or contains at least one non-printable character

Example : Working of isspace()

s = '   \t'
print(s.isspace())

s = ' a '
print(s.isspace())

s = ''
print(s.isspace())

Output

True
False
False

Python String istitle()

The istitle() returns True if the string is a titlecased string. If not, it returns False.The syntax of istitle() method is:

string.istitle()

istitle() Parameters

The istitle() method doesn't take any parameters.


Return Value from istitle()

The istitle() method returns:

  • True if the string is a titlecased string
  • False if the string is not a titlecased string or an empty string

Example : Working of istitle()

s = 'Python Is Good.'
print(s.istitle())

s = 'Python is good'
print(s.istitle())

s = 'This Is @ Symbol.'
print(s.istitle())

s = '99 Is A Number'
print(s.istitle())

s = 'PYTHON'
print(s.istitle())

Output

True
False
True
True
False

Python String isupper()

The string isupper() method returns whether or not all characters in a string are uppercased or not.

The syntax of isupper() method is:

string.isupper()

String isupper() Parameters

The isupper() method doesn't take any parameters.


Return value from String isupper() 

The isupper() method returns:

  • True if all characters in a string are uppercase characters
  • False if any characters in a string are lowercase characters

Example : Return value of isupper()

# example string
string = "THIS IS GOOD!"
print(string.isupper());

# numbers in place of alphabets
string = "THIS IS ALSO G00D!"
print(string.isupper());

# lowercase string
string = "THIS IS not GOOD!"
print(string.isupper());

Output

True
True
False

Python String join()

The join() string method returns a string by joining all the elements of an iterable, separated by a string separator.The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

The syntax of the join() method is:

string.join(iterable)

Return Value from join() method

The join() method returns a string created by joining the elements of an iterable by string separator.

Example:

x=('A','B','C')
print('&'.join(x)
Output : A&B&C

Python String ljust()

The string ljust() method returns a left-justified string of a given minimum width.

The syntax of ljust() method is:

string.ljust(width[, fillchar])

Here, fillchar is an optional parameter.

Example : Left justify string of minimum width

# example string
string = 'cat'
width = 5

# print left justified string
print(string.ljust(width))
print(string.ljust(width),'*')

Output

cat  
cat**

Here, the minimum width defined is 5. So, the resultant string is of minimum length 5.

And, the string cat is aligned to the left which makes leaves two spaces on the right of the wordThe syntax of ljust() method is:

string.ljust(width[, fillchar])

Python String rjust()

The string rjust() method returns a right-justified string of a given minimum width.

The syntax of rjust() method is:

string.rjust(width[, fillchar])

Here, fillchar is an optional parameter.

Example 1: Right justify string of minimum width

# example string
string = 'cat'
width = 5

# print right justified string
print(string.rjust(width))
print(string.rjust(width),'&'))

Output

  cat
&&cat

Here, the minimum width defined is 5. So, the resultant string is at least of length 5.

Now, rjust() aligns the string cat to the right leaving two spaces to the left of the word.

Python String lower()

The string lower() method converts all uppercase characters in a string into lowercase characters and returns it.

The syntax of lower() method is:

string.lower()

Example : Convert a string to lowercase

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())

# string with numbers
# all alphabets whould be lowercase
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

Output

this should be lowercase!
th!s sh0uld b3 l0w3rcas3!

Python String upper()

The string upper() method converts all lowercase characters in a string into uppercase characters and returns it.The syntax of upper() method is:

string.upper()

Example : Convert a string to uppercase

# example string
string = "this should be uppercase!"
print(string.upper())

# string with numbers
# all alphabets whould be lowercase
string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())

Output

THIS SHOULD BE UPPERCASE!
TH!S SH0ULD B3 UPP3RCAS3!

Python String swapcase()

The string swapcase() method converts all uppercase characters to lowercase and all lowercase characters to uppercase characters of the given string, and returns it.The format of swapcase() method is:

string.swapcase()

Example : Swap lowercase to uppercase and vice versa using swapcase()

# example string
string = "THIS SHOULD ALL BE LOWERCASE."
print(string.swapcase())

string = "this should all be uppercase."
print(string.swapcase())

string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase())

Output

this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.

Note: If you want to convert string to lowercase only, use lower(). Likewise, if you want to convert string to uppercase only, use upper().

Python String lstrip()

The lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed).The lstrip() removes characters from the left based on the argument (a string specifying the set of characters to be removed).

The syntax of lstrip() is:

string.lstrip([chars])

Example: Working of lstrip()

random_string = '   this is good '

# Leading whitepsace are removed
print(random_string.lstrip())

# Argument doesn't contain space
# No characters are removed.
print(random_string.lstrip('sti'))

print(random_string.lstrip('s ti'))


Output

this is good 
   this is good 
his is good 

Python String rstrip()

The rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed).The rstrip() removes characters from the right based on the argument (a string specifying the set of characters to be removed).

The syntax of rstrip() is:

string.rstrip([chars])

Example: Working of rstrip()

random_string = 'this is good    '

# Trailing whitepsace are removed
print(random_string.rstrip())

# Argument doesn't contain 'd'
# No characters are removed.
print(random_string.rstrip('si oo'))

print(random_string.rstrip('sid oo'))


Output

this is good
this is good
this is g

Python String strip()

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).The strip() method removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).

The syntax of the strip() method is:

string.strip([chars])

Example: Working of the strip() method

string = 'android is awesome'
print(string.strip('an'))

Output

droid is awesome

Python String partition()

The partition() method splits the string at the first occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.The syntax of partition() is:

string.partition(separator)

Example: How partition() works?

string = "Python is fun"

# 'is' separator is found
print(string.partition('is '))

# 'not' separator is not found
print(string.partition('not '))

string = "Python is fun, isn't it"

# splits at first occurence of 'is'
print(string.partition('is'))

Output

('Python ', 'is ', 'fun')
('Python is fun', '', '')
('Python ', 'is', " fun, isn't it")

Python String maketrans()

The string maketrans() method returns a mapping table for translation usable for translate() method.The syntax of maketrans() method is:

string.maketrans(x[, y[, z]])

Here, y and z are optional arguments.

Example : Translation table using a dictionary with maketrans()

# example dictionary
dict = {"a": "123", "b": "456", "c": "789"}
string = "abc"
print(string.maketrans(dict))

# example dictionary
dict = {97: "123", 98: "456", 99: "789"}
string = "abc"
print(string.maketrans(dict))

Output

{97: '123', 98: '456', 99: '789'}
{97: '123', 98: '456', 99: '789'}
Here, a dictionary dict is defined. It contains a mapping of characters a,b and c to 123, 456, and 789 respectively.

maketrans() creates a mapping of the character's Unicode ordinal to its corresponding translation.

So, 97 ('a') is mapped to '123', 98 'b' to 456 and 99 'c' to 789. This can be demonstrated from the output of both dictionaries.

Python String rpartition()

The rpartition() splits the string at the last occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.The syntax of rpartition() is:

string.rpartition(separator)

Example: How rpartition() works?

string = "Python is fun"

# 'is' separator is found
print(string.rpartition('is '))

# 'not' separator is not found
print(string.rpartition('not '))

string = "Python is fun, isn't it"

# splits at last occurence of 'is'
print(string.rpartition('is'))

Output

('Python ', 'is ', 'fun')
('', '', 'Python is fun')
('Python is fun, ', 'is', "n't it")

Python String translate()

The string translate() method returns a string where each character is mapped to its corresponding character in the translation table.translate() method takes the translation table to replace/translate characters in the given string as per the mapping table.

The translation table is created by the static method maketrans().

The syntax of the translate() method is:

string.translate(table)

Example : Translation/Mapping using a translation table with translate()

# first string
firstString = "abc"
secondString = "ghi"
thirdString = "ab"

string = "abcdef"
print("Original string:", string)

translation = string.maketrans(firstString, secondString, thirdString)

# translate string
print("Translated string:", string.translate(translation))

Output

Original string: abcdef
Translated string: idef

Python String replace()

The replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring.The syntax of replace() is:

str.replace(old, new [, count]) 

Example : Using replace()

song = 'cold, cold heart'

# replacing 'cold' with 'hurt'
print(song.replace('cold', 'hurt'))

song = 'Let it be, let it be, let it be, let it be'

# replacing only two occurences of 'let'
print(song.replace('let', "don't let", 2))

Output

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

Python String rfind()

The rfind() method returns the highest index of the substring (if found). If not found, it returns -1.The syntax of rfind() is:

str.rfind(sub[, start[, end]] )

Example : rfind() With No start and end Argument

quote = 'Let it be, let it be, let it be'

result = quote.rfind('let it')
print("Substring 'let it':", result)

result = quote.rfind('small')
print("Substring 'small ':", result)

Output

Substring 'let it': 22
Substring 'small ': -1

Python String rindex()

The rindex() method returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.The syntax of rindex() is:

str.rindex(sub[, start[, end]] )

Example : rindex() With No start and end Argument

quote = 'Let it be, let it be, let it be'

result = quote.rindex('let it')
print("Substring 'let it':", result)
  
result = quote.rindex('small')
print("Substring 'small ':", result)

Output

Substring 'let it': 22
Traceback (most recent call last):
  File "...", line 6, in <module>
    result = quote.rindex('small')
ValueError: substring not found

Python String split()

The split() method breaks up a string at the specified separator and returns a list of strings.The syntax of split() is:

str.split([separator [, maxsplit]])

Example : How split() works in Python?

text= 'Love thy neighbor'

# splits at space
print(text.split())

grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.split(', '))

# Splitting at ':'
print(grocery.split(':'))

Output

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']

Python String rsplit()

The rsplit() method splits string from the right at the specified separator and returns a list of strings.The syntax of rsplit() is:

str.rsplit([separator [, maxsplit]])

Example : How rsplit() works in Python?

text= 'Love thy neighbor'

# splits at space
print(text.rsplit())

grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.rsplit(', '))

# Splitting at ':'
print(grocery.rsplit(':'))

Output

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']

Python String splitlines()

The splitlines() method splits the string at line breaks and returns a list of lines in the string.

The syntax of splitlines() is:

str.splitlines([keepends])

Example: How splitlines() works?

grocery = 'Milk\nChicken\r\nBread\rButter'

print(grocery.splitlines())
print(grocery.splitlines(True))

grocery = 'Milk Chicken Bread Butter'
print(grocery.splitlines())

Output

['Milk', 'Chicken', 'Bread', 'Butter']
['Milk\n', 'Chicken\r\n', 'Bread\r', 'Butter']
['Milk Chicken Bread Butter']

Python String startswith()

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False.The syntax of startswith() is:

str.startswith(prefix[, start[, end]])

Example : startswith() Without start and end Parameters

text = "Python is easy to learn."

result = text.startswith('is easy')
# returns False
print(result)

result = text.startswith('Python is ')
# returns True
print(result)

result = text.startswith('Python is easy to learn.')
# returns True
print(result)

Output

False
True
True

Python String title()

The title() method returns a string with first letter of each word capitalized; a title cased string.The syntax of title() is:

str.title()

Example : How Python title() works?

text = 'My favorite number is 25.'
print(text.title())

text = '234 k3l2 *43 fun'
print(text.title())

Output

My Favorite Number Is 25.
234 K3L2 *43 Fun

Python String zfill()

The zfill() method returns a copy of the string with '0' characters padded to the left.The syntax of zfill() in Python is:

str.zfill(width)

Example : How zfill() works in Python?

text = "program is fun"
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))

Output

0program is fun
000000program is fun
program is fun


Comments