Skip to content

Commit 3c9fbd2

Browse files
committed
Add string.py to demonstrate string operations and methods in Python
1 parent 920483f commit 3c9fbd2

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

String/string.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Basic print
2+
print("Hello world!")
3+
4+
chai = "masala chai"
5+
print(chai)
6+
7+
chai = "ginger chai"
8+
print(chai)
9+
10+
# Accessing characters and slices
11+
first_char = chai[0]
12+
print("First character:", first_char)
13+
14+
slice_chai = chai[0:6]
15+
print("First 6 characters:", slice_chai)
16+
17+
slice_chai = chai[-1]
18+
print("Last character:", slice_chai)
19+
20+
# Slicing a string
21+
num_list = "0123456789"
22+
print(num_list[:7]) # 0 to 6
23+
print(num_list[3:]) # From index 3 to end
24+
print(num_list[:]) # Full string
25+
print(num_list[0:7:2]) # 0 to 6 with step 2
26+
print(num_list[0:7:3]) # 0 to 6 with step 3
27+
28+
# String methods
29+
print(chai.lower()) # Lowercase
30+
print(chai.upper()) # Uppercase
31+
print(chai.strip()) # Remove leading/trailing spaces
32+
print(chai.replace("lemon", "ginger")) # Doesn't find "lemon" in current string, so unchanged
33+
34+
# Reassign and use more methods
35+
chai = "Lemon Ginger Masala Mint"
36+
print(chai.split(", ")) # Only works with comma+space, returns entire string as 1 element
37+
print(chai.find("Lemon")) # Index of "Lemon"
38+
print(chai.count("lemon")) # Case-sensitive → 0
39+
40+
# String formatting
41+
chai_type = "Masala"
42+
quantity = 2
43+
order = "I ordered {} cups of {} tea"
44+
print(order.format(quantity, chai_type))
45+
46+
# List joining
47+
chai_variety = ["Lemon", "Masala", "Ginger"]
48+
print(" ".join(chai_variety)) # Space-separated
49+
print("-".join(chai_variety)) # Hyphen-separated
50+
51+
# String length
52+
print(len(chai))
53+
54+
# Fixed: for loop syntax (add colon at end)
55+
for letter in chai:
56+
print(letter)
57+
58+
# Raw string
59+
chai = r"Masala\chai"
60+
print(chai)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy