0% found this document useful (0 votes)
27 views9 pages

18-10-2024 Afternoon

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views9 pages

18-10-2024 Afternoon

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

STRING & STRING MANIPULATIONS IN PYTHON

-----------------------------------------------------------

C Language: char na[50] = "Anushya S";


Java Language: String na = "Anushya S";

What is a String?
String is a group of characters (alphabets both uppercase & lowercase, digits, and
special characters)
enclosed within quotations.
NOTE: There is no char data type in Python. So, even a single character is treated
as a String.
Ex: language = 'C' --> String
C --> char language = 'C'; --> char type - 1 byte
Java --> char language = 'C'; --> char type - 2 byte

1. It can be created in 3 ways: Single, Double, Triple Quotes

Example:
# Single Quoted String
s1 = 'Python 3.12'
print("Type =", type(s1))
print("Value =", s1)
print()

# Double Quoted String


# Output: I am enjoying 'Java' very much!
s2 = "I am enjoying 'Java' very much!"
print("Type =", type(s2))
print("Value =", s2)
print()

# Triple Quoted String: Multiline Strings


s3 = ''' Python
Rocks '''
print("Type =", type(s3))
print("Value =", s3)
print()

s4 = """ Python
Rules! """
print("Type =", type(s4))
print("Value =", s4)
print()

Output:
Type = <class 'str'>
Value = Python 3.12

Type = <class 'str'>


Value = I am enjoying 'Java' very much!

Type = <class 'str'>


Value = Python
Rocks

Type = <class 'str'>


Value = Python
Rules!
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
2. Strings are IMMUTABLE -> cannot be modified
In Python - MUTABLE TYPES are: list, dict, set

Example:
s = "C++"
print("String =" , s)
print("Address of String =", id(s))

s = "Java"
print("String =" , s)
print("Address of String =", id(s))

Output:
String = C++
Address of String = 2657202361120
String = Java
Address of String = 2657162934384

Example:
s = "java"
print("String =" , s)
print("Address of String =", id(s))
print()

# Converts the String into Uppercase and produces a string as a result


r = s.upper()

print("Orinignal String =" , s)


print("Address of String =", id(s))
print()
print("Modified String =" , r)
print("Address of String =", id(r))

Output:
String = java
Address of String = 2413110471360

Orinignal String = java


Address of String = 2413110471360

Modified String = JAVA


Address of String = 2413110310112
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
3. It is an iterable - can be looped over
All the type of loops can be used to iterate over a String --> while,
variations of for

Example:
# Reading the Input from the user
s = input("Enter the String: ")

# Simple for Loop


print("Simple For Loop")
for ele in s:
print(ele)
print()

# for Loop with range()


print("for Loop with range()")
for i in range(0, len(s), 1):
print(i,s[i])
print()

# for Loop with enumerate()


print("for Loop with enumerate()")
for x in enumerate(s):
print(x)
print()

for x,y in enumerate(s):


print(x,y)
print()

# while Loop
print("while Loop")
i = 0
while i < len(s):
print(i,s[i])
i+=1
print()
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
4. Data is stored internally based on indexes (Random Access)

NOTE: 3 types in Python are Index Based: Lists, Strings and Tuples

In Python we have 2 types of Indexes:


N = length of the String;
a. Positive Index: Forward direction --> 0 to N-1
b. Negative Index: Backward direction --> -1 to -N

Example:
s = "welcome Anu!"

''' INTERNAL STORAGE


0 1 2 3 4 5 6 7 8 9 10
11
w e l c o m e A n u
!
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
'''

# Accessing Individual Elements


print(s[0])
print(s[-1])
print(s[3])
print(s[-6])

# Invalid Index will generate Error - IndexError: string index out of range
print(s[100])
print(s[-20])
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
5. Slicing can be applied

Syntax:
String [start: stop: step]

NOTE: When we slice a string, the result we get is also a string


Direction is decided based on the STEP value

Example:
s = "welcome Anu!"

''' INTERNAL STORAGE


0 1 2 3 4 5 6 7 8 9 10
11
w e l c o m e A n u
!
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2
-1
'''

# Default Step Value = 1 ; Forward direction - from start to end


print(s[ : : ]) # welcome Anu!

# Step Value = 1 ; Forward direction - from start to end


print(s[ : :1]) # welcome Anu!

# Step Value = -1 ; Backward direction - from start to end


# Printitng the String in Reverse Order
print(s[::-1])

# Every 3rd character from the String: Forward direction - start to end
print(s[::3])

# From index 2 to Index -3 the characters will be fetched: Forward direction


print(s[2:-2:1]) # lcomeAn

# Default Step Value = 1 ; Clash in direction - Empty String will be produced as a


result
print(s[-2:0]) # ""

# Invalid index positions in slicing - NO IndexError will be generated


# Default Step Value = 1; starting from index 0 till the end of the string slicing
will happen
print(s[0:500]) # welcome Anu!

# Invalid index positions in slicing - NO IndexError will be generated


# Default Step Value = 1; Starting from -N to index 4 slicing will happen
print(s[-400:5]) # welco
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Interview Questions

1. What will be the Output?


str = "programming"
print(str[0])
print(str[-1])
print(str[1:5])
print(str[5:-2])
print(str[::1])
print(str[::-1])

Original String: "programming"


0 1 2 3 4 5 6 7 8 9
10
p r o g r a m m i n
g
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2
-1
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
2. What will be the Output?
s="Python"
print(s[::-5])
print(s[::-1][::-5])
print(s[0]+s[-1])
print(s[::5])
print(s[::-1][-1]+s[len(s)-1])

Original String: "Python"


0 1 2 3 4 5
P y t h o n
-6 -5 -4 -3 -2 -1

Reversed String: "nohtyP"


0 1 2 3 4 5
n o h t y P
-6 -5 -4 -3 -2 -1
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
3. What will be the Output?

s = "PYTHON PROGRAMMING"
print(s[::-2])
print(s[2:3])
print(s[2:3:-1])
print(s[-6:7:-2])
print(s[4:-8])
print(s[9:-10])
print(s[22::-6])
print(s[2:-22:-1])
print(s[7::-1])
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
6. Operator '+' does the work of concatenation / joining

Example:
s1 = "Welcome"
s2 = "to"
s3 = "Python"

s = s1 + ' ' + s2 + ' ' + s3


print("Concatenated String:",s)

Output:
Concatenated String: Welcome to Python
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
7. Operator '*' does the work of repetition
Example:
s = "Welcome"
newStr = s * 3
print("Repeated String:" , newStr)

Output:
Repeated String: WelcomeWelcomeWelcome
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
8. Membership Operators: in, not in
Used for the purpose of searching whether the given sub-string exists within the
specified string or not.
Boolean value is returned as the output. Case Sensitive

• in: Returns True if a character exists within the given string otherwise False.
• not in: Returns True if a character does not exist in the given string otherwise
returns False.

Example:
str = "Program"

print(f"Is 'gram' not present in the String?: {'gram' not in str}")


print(f"Is 'grams' not present in the String?: {'grams' not in str}")
print()
print(f"Is 'a' present in the String?: {'a' in str}")
print(f"Is 'z' present in the String?: {'z' in str}")

Output:
Is 'gram' not present in the String?: False
Is 'grams' not present in the String?: True

Is 'a' present in the String?: True


Is 'z' present in the String?: False

Example:
string = input("Enter the String: ")
search = input("Enter the string to search: ")

if search in string:
print("Found")
else:
print("Not Found")
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
9. Raw string - It is used to supresses the effects of the escape sequences used
within the string.

Example:
print("This is \ngood\texample")
print()
print(r"This is \ngood\texample")
print(R"This is \ngood\texample")

NOTE:
The same Job can also be done using the repr() function. The difference is that the
output will be within single quotation.

Example:
print(repr("I \nLove\tPython"))

Output:
'I \nLove \tPython'
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Built-In String Functions

String have a very wide range of pre-defined functions.


General Syntax:
str.FunctionName()

1. len():
Syntax --> len(string)
returns the length of the string and if the string is empty it returns 0

2. upper():
Syntax --> str.upper()
converts the string into uppercase and returns a new string as the result

3. lower():
Syntax --> str.lower()
converts the string into lowercase and returns a new string as the result

Example:
s = input("Enter the String: ")
print(F"Length of the String = {len(s)}")
print(F"String in Uppercase = {s.upper()}")
print(F"String in Lowercase = {s.lower()}")

4. capitalize():
Syntax --> str.capitalize()
converts the entire string into lowercase alphabets except the 1st character,
which will be in uppercase.

Example:
s = "PYTHON Programming is SO Cool!"
print(F"String = {s}")
print(F"Capitalized String = {s.capitalize()}")

5. center():
Syntax --> str.center(width, character)
character is Optional; If not mentioned the default value is a single space.
Decoration Purpose

Example:
s = "PYTHON"
print(F"String = {s}")
print(s.center(50))
print(s.center(50, '*'))

6. count():
Syntax --> str.count(character, start, end)
start and end are Optional values. They are used when we want to search within
a specific range
It will return the number of occurrences of the specified character within the
given string.
Case sensitive search is performed.
Example:
s = "Welcome to python programming. Python is such a cool language. python is so
easy to learn"
print(F"String = {s}")
print()

print(F"Number of time 'o' occurs = {s.count('o')}")


print(F"Number of time 'z' occurs = {s.count('z')}")
print(F"Number of time 'python' occurs = {s.count('python')}")
print(F"Number of time 'python' occurs = {s.count('python', 25)}")
print(F"Number of time 'python' occurs = {s.count('python', 25, 35)}")

7. startswith():
Boolean Function
Syntax --> str.startswith(starting_char, start, end)
start and end are optional parameters; They are used when we want to search
within a specific range
It will check whether the given string starts with the specified characters.
Case Sensitive

8. endswith()
Boolean Function
Syntax --> str.endswith(ending_char, start, end)
start and end are optional parameters; They are used when we want to search
within a specific range
It will check whether the given string ends with the specified characters.
Case Sensitive

Example:
s = "Welcome to python programming."
print(F"String = {s}")
print()
print(F"Starts with 'Wel' = {s.startswith('Wel')}")
print(F"Ends with 'ing' = {s.endswith('ing')}")
print(F"Ends with 'ing.' = {s.endswith('ing.')}")
print()
print(F"Starts with 'py' from Index 11 = {s.startswith('py', 11)}")

9. find()
10. rfind()
11. index()
12. rindex()
13. title()
14. join()
15. ljust()
16. rjust()
17. swapecase()
18. lstrip()
19. rstrip()
20. strip()
21. replace()
22. split()
23. rsplit()
24. max()
25. min()

NOTE: All the functions starting with 'is' are Boolean - result will be either True
(or) False
26. isalpha()
27. isdigit()
28. isnumeric()
29. isdecimal()
30. isidentifier()
31. isprintable()
32. isspace()
33. istitle()
34. isupper()
35. islower()

Note:
Difference between find() and index() Functions
Difference between title() and capitalize() Functions
Difference between isdigit(), isnumeric() and isdecimal()

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

You might also like