forked from singhsanket143/Unacademy_Pec_Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString_In_Python.py
110 lines (73 loc) · 2.02 KB
/
String_In_Python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
1. Indexing of String -> Strings in python are 0-indexed
s = 'codechef'
s[0] = 'c'
s[1] = 'o'
s[2] = 'd'
.....
s[len(s) - 1] = 'f'
In python Strings are also indexed from -1 if we start from last character to the first
s[-1] = 'f'
s[-2] = 'e'
s[-3] = 'h'
"""
s = "codechef"
print(s[0], s[1], s[2], s[3], s[4], s[len(s) - 1])
print(s[-1], s[-2], s[-3], s[-4])
# -------------------------------------------
"""
2. Multiline strings -> we can have multiline strings using triple quotes
triple quotes can be either triple double quotes or triple single quotes
"""
a = """Thisis
amultiline
string
"""
b = '''
Thisis
amultiline
string'''
c = a + b
# print(a, b)
# print("Result of concatenation = ", c)
print(b[0], b[1], b[2], b[-1], len(b))
"""
if you have a multiline string which starts from a new line like b, then
on the 0th index we will have new line character and the first character will be at index 1
whereas if we have a string like a, which starts just after quotes then
first char is at index 0
"""
print(a[0], a[1], a[2], a[-1], len(a))
# -------------------------------------------
"""
3. Operators on strings
"""
first = "Sanket"
last = "Singh"
middle = "Singh"
print(first + last) # concatenation
print(first*3) # repition of string
# Comparison operators
print(first == last) # -> False
print(last == middle) # -> True
print(last != first) # -> True
print(last != middle) # -> False
# Comparison based on dictionary order
print("abc" < "def") # -> Acc to dictionary it should be yes
print("camel" > "apple") # -> true
print("Singh" == "singh") #-> false
print("Singh" > "singh") # based on ascii
print("aa" < "aab") # in dictionary also aa comes before aab
# membership operator
print("a" in first)
print("aa" in first)
print("ab" not in first)
# -------------------------------------------
"""
4. Mutability in strings
"""
li = [1,2,3,4,5]
li[2] = 22 # this will work
# why it works for list ??? because lists are mutable/updatable
st = "codechef"
st[2] = 'r' # this wont work because strings are not mutable