-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.py
More file actions
97 lines (75 loc) · 2.04 KB
/
string.py
File metadata and controls
97 lines (75 loc) · 2.04 KB
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
# Basic print
print("Hello world!")
chai = "masala chai"
print(chai)
chai = "ginger chai"
print(chai)
# Accessing characters and slices
first_char = chai[0]
print("First character:", first_char)
slice_chai = chai[0:6]
print("First 6 characters:", slice_chai)
slice_chai = chai[-1]
print("Last character:", slice_chai)
# Slicing a string
num_list = "0123456789"
print(num_list[:7]) # 0 to 6
print(num_list[3:]) # From index 3 to end
print(num_list[:]) # Full string
print(num_list[0:7:2]) # 0 to 6 with step 2
print(num_list[0:7:3]) # 0 to 6 with step 3
# String methods
print(chai.lower()) # Lowercase
print(chai.upper()) # Uppercase
print(chai.strip()) # Remove leading/trailing spaces
print(chai.replace("lemon", "ginger")) # Doesn't find "lemon" in current string, so unchanged
# Reassign and use more methods
chai = "Lemon Ginger Masala Mint"
print(chai.split(", ")) # Only works with comma+space, returns entire string as 1 element
print(chai.find("Lemon")) # Index of "Lemon"
print(chai.count("lemon")) # Case-sensitive → 0
# String formatting
chai_type = "Masala"
quantity = 2
order = "I ordered {} cups of {} tea"
print(order.format(quantity, chai_type))
# List joining
chai_variety = ["Lemon", "Masala", "Ginger"]
print(" ".join(chai_variety)) # Space-separated
print("-".join(chai_variety)) # Hyphen-separated
# String length
print(len(chai))
# Fixed: for loop syntax (add colon at end)
for letter in chai:
print(letter)
# Raw string
chai = r"Masala\chai"
print(chai) # Output: Masala\chai
# Multiline Strings
multiline_chai="""
Masala Chai Recipe:
- Water
- Tea Leaves
- Spices
- Milk
- Sugar
- Enjoy!
"""
print(multiline_chai)
multiline_kashmiri_chai = '''
Kashmiri Chai Recipe:
- kashmiri packed tea packet
- Almonds
- Hot Milk
- Sugar
- Enjoy!
'''
print(multiline_kashmiri_chai)
txt = "The best things in life are free!"
print("The" in txt) # True
print("expensive" not in txt) # True
age=18
txt=f"age of waseem is {age}"
print(txt)
opr = f"the sum of 5+7 is {5+7}"
print(opr)