Sayantan's Blog On Python Programming

PYTHON STRING MANIPULATION

PYTHON STRING MANIPULATION

PYTHON STRING VARIABLES

Variables are the container that store sting values. Actually it is a name given to a memory location where the string value is stored .The advantage of using a variable is if we change the value stored in the variable then it will change all the dependent values where the variable is referenced.

PYTHON STRING CONCATENATION

CONCATENATION OPERATOR

In Python + operator are used as concatenation operator. But this is a manual concatenation.

# STRING CONCATENATION example

print("\nHey how are you? " + "I'm learning Python nowadays!" + " What about you?")

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

# STRING CONCATENATION USING VARIABLE example

str_var = "I'm learning Python nowadays!"

print("\nHey how are you? " + str_var + "What about you?")

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays!What about you?

USING f PREFIX

f prefix accepts an expression inside it. Anything enclosed with curly braces indicates that it is a variable.

# STRING CONCATENATION USING f PREFIX example

str_var = "I'm learning Python nowadays!"

print(f'\nHey how are you? {str_var} What about you?')

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

If we exclude the f prefix then the entire format including {str_var}will be printed as a string.

# STRING CONCATENATION WITHOUT USING f PREFIX example

str_var = "I'm learning Python nowadays!"

print('\nHey how are you? {str_var} What about you?')

PYTHON STRING MANIPULATION : Output

Hey how are you? {str_var} What about you?

f prefix can be worked with double quotes as well.

# STRING CONCATENATION USING f PREFIX example

str_var = "I'm learning Python nowadays!"

print(f"\nHey how are you? {str_var} What about you?")

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

f prefix can also worked with triple single quotes and triple double quotes.

# STRING CONCATENATION USING f PREFIX example

str_var = "I'm learning Python nowadays!"

print(f'''\nHey how are you? {str_var} What about you?''')

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

# STRING CONCATENATION USING f PREFIX example

str_var = "I'm learning Python nowadays!"

print(f"""\nHey how are you? {str_var} What about you?""")

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

USING .format Function

# STRING CONCATENATION USING .format FUNCTION example

str_var = "I'm learning Python nowadays!"

print("\nHey how are you? {} What about you?".format(str_var))

PYTHON STRING MANIPULATION : Output

Hey how are you? I'm learning Python nowadays! What about you?

PYTHON BUILT-IN FUNCTIONS FOR STRINGS

print()

print() function is used to print a string variable.

# print() FUNCTION example

str_var = "\nI'm learning Python nowadays!"

print(str_var)

PYTHON STRING MANIPULATION : Output

I'm learning Python nowadays!

type()

# type() FUNCTION example

str_var = "\nI'm learning Python nowadays!"

print("\nData type of str_var -> ", type(str_var))

PYTHON STRING MANIPULATION : Output

Data type of str_var ->  <class 'str'>

len()

len() function is returned the length of a string.

# len() FUNCTION example

str_var = "\nI'm learning Python nowadays!"

print(str_var)
print("\nLength of str_var -> ", len(str_var))

PYTHON STRING MANIPULATION : Output

I'm learning Python nowadays!

Length of str_var ->  30

count()

count() function returns the no of occurrence of a substring inside a large string.

# count() FUNCTION example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nCount of n in str_var -> ", str_var.count('n'))

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Count of n in str_var ->  4

Membership Function:

Membership function check whether a substring is present in a large string or not. If the substring is present then Python returns TRUE and otherwise returns FALSE.

# MEMBERSHIP FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nPython is present in str_var -> ", 'Python' in str_var)

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Python is present in str_var ->  True

# MEMBERSHIP FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nJava is present in str_var -> ", 'Java' in str_var)

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Java is present in str_var ->  False

upper()

upper() converts the entire string into upper case.

# upper FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nUpper value of str_var -> ", str_var.upper())

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Upper value of str_var ->  
I'M LEARNING PYTHON NOWADAYS!

isupper()

isupper() function returns TRUE if all the characters of a string are in upper case. Otherwise Python will return FALSE.

# isupper FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nResult of isupper function -> ", str_var.isupper())

str_var = str_var.upper()

print("\nOriginal String -> ", str_var)
print("\nResult of isupper function -> ", str_var.isupper())

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Result of isupper function ->  False

Original String ->  
I'M LEARNING PYTHON NOWADAYS!

Result of isupper function ->  True

lower()

# lower FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nLower value of str_var -> ", str_var.lower())

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Lower value of str_var ->  
i'm learning python nowadays!

islower()

islower() function returns TRUE if all the characters of a string are in lower case. Otherwise Python will return FALSE.

# islower FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nResult of islower function -> ", str_var.islower())

str_var = str_var.lower()

print("\nOriginal String -> ", str_var)
print("\nResult of islower function -> ", str_var.islower())

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Result of islower function ->  False

Original String ->  
i'm learning python nowadays!

Result of islower function ->  True

title()

title() function converts a string into title case.

# title FUNCTION IN STRING example

str_var = "\nI'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nTitle value of islower function -> ", str_var.title())

PYTHON STRING MANIPULATION : Output

Original String ->  
I'm learning Python nowadays!

Title value of islower function ->  
I'M Learning Python Nowadays!

istitle()

istitle() function returns TRUE if all the characters of a string are in title case. Otherwise Python will return FALSE.

# istitle FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nResult of istitle function -> ", str_var.istitle())

str_var = str_var.title()

print("\nOriginal String -> ", str_var)
print("\nResult of istitle function -> ", str_var.istitle())

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Result of istitle function ->  False

Original String ->  I'M Learning Python Nowadays!

Result of istitle function ->  True

capitalize()

# capitalize FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)
print("\nCapitalize value of str_var -> ", str_var.capitalize())

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Capitalize value of str_var ->  I'm learning python nowadays!

find()

find() function returns the position of first occurrence of a substring inside a large string. If the substring is not found in large string then Python returns -1.

# find FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\n1st occurrence of n in str_var -> ", str_var.find('n'))
print("\n1st occurrence of z in str_var -> ", str_var.find('z'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

1st occurrence of n in str_var ->  8

1st occurrence of z in str_var ->  -1

rfind()

rfind() function returns the highest index position of a substring inside a large string.

# rfind FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nHighest position of n in str_var -> ", str_var.rfind('n'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Highest position of n in str_var ->  20

index()

index() function is the extended version of find() function. find() function always returns the lowest position of a string inside a large string. But in index() function we can provide index position of search for the substring. Index searching is always starts with position 0.

# index FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\n1st occurrence of n in str_var -> ", str_var.index('n', 1, 10)), 

print("\n2nd occurrence of n in str_var -> ", str_var.index('n', 11, 19)), 

print("\n3rd occurrence of n in str_var -> ", str_var.index('n', 19, len(str_var)))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

1st occurrence of n in str_var ->  8

2nd occurrence of n in str_var ->  18

3rd occurrence of n in str_var ->  20

if a substring is not found in a given index range then Python will raise an error.

# index FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\n1st occurrence of n in str_var -> ", str_var.index('n', 1, 10)), 

print("\n2nd occurrence of n in str_var -> ", str_var.index('n', 11, 19)), 

print("\n3rd occurrence of n in str_var -> ", str_var.index('n', 21, len(str_var)))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

1st occurrence of n in str_var ->  8

2nd occurrence of n in str_var ->  18
Traceback (most recent call last):
  File "d:\PYTHON\PROGRAM\tempCodeRunnerFile.python", line 14, in <module>
    print("\n3rd occurrence of n in str_var -> ", str_var.index('n', 21, len(str_var)))
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: substring not found

In the above example for first two search Python has found the substring n. But in the third search n is not found and Python has raised the error “Substring not found“.

rindex()

rindex() function returns the highest index position of a substring inside a string in a given index range.

# rindex FUNCTION IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nHighest position of n in str_var -> ", str_var.rindex('n'))
print("\nHighest position of n in str_var between 1 and 9 -> ", str_var.rindex('n', 1, 9))
print("\nHighest position of n in str_var between 1 and 11 -> ", str_var.rindex('n', 1, 11))
print("\nHighest position of n in str_var between 1 and 19 -> ", str_var.rindex('n', 1, 19))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Highest position of n in str_var ->  20

Highest position of n in str_var between 1 and 9 ->  8

Highest position of n in str_var between 1 and 11 ->  10

Highest position of n in str_var between 1 and 19 ->  18

Slicing operator in Python [:]

Slicing operator helps to extract a substring from a large string based on the index range specified.

# slicing operator [:] IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nShowing complete string in str_var -> ", str_var[:])
print("\nShowing first 12 characters of str_var -> ", str_var[:12])
print("\nShowing characters between 13 and 19 of str_var -> ", str_var[13:19])

# Negative index in slicing  operation

print("\nShowing str_var excluding 10 characters from the end -> ", str_var[:-10])

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Showing complete string in str_var ->  I'm learning Python nowadays!

Showing first 12 characters of str_var ->  I'm learning

Showing characters between 13 and 19 of str_var ->  Python

Showing str_var excluding 10 characters from the end ->  I'm learning Python

Negative indexes are used to extract the substring from the end or from right to left.

swapcase()

swapcase() function converts all the string characters to its opposite case. If any letter is in uppercase then it will be converted to lowercase and vice versa.

# swapcase function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nSwap result of str_var -> ", str_var.swapcase())

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Swap result of str_var ->  i'M LEARNING pYTHON NOWADAYS!

startswith()

startswith() function returns TRUE if a string is starts with a given letter. Otherwise Python will return FALSE.

# endswith function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nString starts with I -> ", str_var.startswith('I'))

print("\nString starts with i -> ", str_var.startswith('i'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

String starts with I ->  True

String starts with i ->  False

Since Python is case sensitive that’s why I and i are different in Python.

endswith()

endswith() returns TRUE if a string ends with a given substring. Otherwise Python will return FALSE.

# endswith function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nString ends with ! -> ", str_var.endswith('!'))

print("\nString ends with days! -> ", str_var.endswith('days!'))

print("\nString ends with s -> ", str_var.endswith('s'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

String ends with ! ->  True

String ends with days! ->  True

String ends with s ->  False

replace()

replace() function replaces a part of a string with a substring.

# replace function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nResult of replace function -> ", str_var.replace('Python', 'Java'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Result of replace function ->  I'm learning Java nowadays!

lstrip()

lstrip() function returns the string with truncating first character. If we don’t mention any character then Python will consider the character to be a white space. Otherwise the given character will be truncated from the beginning.

# lstrip function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nImpact of lstrip on str_var -> ", str_var.lstrip())

print("\nImpact of lstrip on str_var -> ", str_var.lstrip('I'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Impact of lstrip on str_var ->  I'm learning Python nowadays!

Impact of lstrip on str_var ->  'm learning Python nowadays!

rstrip()

rstrip() function returns the string with truncating last character. If we don’t mention any character then Python will consider the character to be a white space. Otherwise the given character will be truncated from the end.

# rstrip function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nImpact of rstrip on str_var -> ", str_var.rstrip())

print("\nImpact of rstrip on str_var -> ", str_var.rstrip('!'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Impact of rstrip on str_var ->  I'm learning Python nowadays!

Impact of rstrip on str_var ->  I'm learning Python nowadays

strip()

strip() function returns the string with truncating last character. If we don’t mention any character then Python will consider the character to be a white space. Otherwise the given character will be truncated both from the beginning and end.

# strip function IN STRING example

str_var = "I'm learning Python nowadays!"

print("\nOriginal String -> ", str_var)

print("\nImpact of strip() on str_var -> ", str_var.strip())
print("\nRemoving first character of str_var by strip() -> ", str_var.strip('I'))
print("\nRemoving last character of str_var by strip() -> ", str_var.strip('!'))

str_var = "!I'm learning Python nowadays!"
print("\nOriginal String -> ", str_var)
print("\nRemoving first and last character of str_var by strip() -> ", str_var.strip('!'))

PYTHON STRING MANIPULATION : Output

Original String ->  I'm learning Python nowadays!

Impact of strip() on str_var ->  I'm learning Python nowadays!

Removing first character of str_var by strip() ->  'm learning Python nowadays!

Removing last character of str_var by strip() ->  I'm learning Python nowadays

Original String ->  !I'm learning Python nowadays!

Removing first and last character of str_var by strip() ->  I'm learning Python nowadays

RELATED TOPICS:

Leave a Comment

Your email address will not be published. Required fields are marked *