0% found this document useful (0 votes)
52 views7 pages

18-10-2024 Morning

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)
52 views7 pages

18-10-2024 Morning

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/ 7

STRING & STRING MANIPULATIONS IN PYTHON

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

What is a String?
String is a group of characters (alphabets both uppercase & lowercase, digits, and
special characters)
enclosed within quotations.

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


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

s4 = """ Python
Rules! """
print("Type =", type(s4))
print("Value =", s4)
print()
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
2. Strings are Immutable -> cannot be modified

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

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[::])

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


print(s[::1])

# 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])

# 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])

# 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])
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
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])
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
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.

• 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
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
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.

1. len()
2. upper()
3. lower()
4. capitalize()
5. center()
6. count()
7. startswith()
8. endswith()
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

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

You might also like