-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.py
More file actions
140 lines (101 loc) · 3.7 KB
/
strings.py
File metadata and controls
140 lines (101 loc) · 3.7 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# String Concepts in Python
# ----------------------------------------------
# 1. INTRODUCTION TO STRINGS
# ----------------------------------------------
# A string is a sequence of characters enclosed in single (' '), double (" "), or triple quotes (''' ''' or """ """)
# Strings are immutable (cannot be changed once created)
# String examples
str1 = 'Hello'
str2 = "Python"
str3 = '''This is a
multi-line string.'''
print("String 1:", str1)
print("String 2:", str2)
print("Multi-line String:\n", str3)
# ----------------------------------------------
# 2. STRING OPERATIONS
# ----------------------------------------------
# Concatenation (Joining Strings)
concat_str = str1 + " " + str2
print("\nConcatenated String:", concat_str)
# Repetition
repeat_str = str1 * 3
print("Repeated String:", repeat_str)
# Indexing (Accessing by position)
print("First character:", str1[0])
print("Last character:", str1[-1])
# Slicing (Extracting substring)
print("Sliced String (0 to 3):", str1[0:4])
print("Sliced String (from index 2):", str1[2:])
print("Sliced String (till index 3):", str1[:3])
# Length of string
print("Length of str2:", len(str2))
# Membership testing
print("'H' in str1:", 'H' in str1)
print("'z' not in str1:", 'z' not in str1)
# ----------------------------------------------
# 3. TRAVERSING A STRING
# ----------------------------------------------
# Traversing means accessing each character in a string, usually with a loop.
sample = "Python"
print("\nTraversing using for loop:")
for ch in sample:
print(ch)
print("\nTraversing using index:")
for i in range(len(sample)):
print("Character at index", i, ":", sample[i])
# ----------------------------------------------
# 4. STRING METHODS AND BUILT-IN FUNCTIONS
# ----------------------------------------------
# Common String Methods
text = " Python Programming Language "
print("\nOriginal Text:", text)
# Case conversion
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
print("Title Case:", text.title())
print("Swap Case:", text.swapcase())
# Whitespace removal
print("Stripped:", text.strip())
# Searching and replacing
print("Find 'Python':", text.find('Python'))
print("Replace 'Python' with 'Java':", text.replace('Python', 'Java'))
# Splitting and joining
words = text.split() # splits string into list
print("Split into words:", words)
joined = "-".join(words)
print("Joined with '-':", joined)
# Counting and checking
print("Count of 'a':", text.count('a'))
print("Starts with 'Py':", text.strip().startswith("Py"))
print("Ends with 'age':", text.strip().endswith("age"))
print("Is Alphabetic:", text.strip().isalpha()) # returns False because spaces exist
# Built-in functions for strings
print("\nBuilt-in Functions:")
print("Length:", len(text))
print("Minimum character:", min(text))
print("Maximum character:", max(text))
print("Sorted characters:", sorted(text))
# ----------------------------------------------
# 5. HANDLING STRINGS
# ----------------------------------------------
# Since strings are immutable, modifications create new strings.
original = "Hello"
modified = original.replace("H", "J")
print("\nOriginal String:", original)
print("Modified String:", modified)
# String formatting
name = "Alice"
age = 21
# Using f-string (modern method)
info1 = f"My name is {name} and I am {age} years old."
print("\nFormatted (f-string):", info1)
# Using format() method
info2 = "My name is {} and I am {} years old.".format(name, age)
print("Formatted (format method):", info2)
# Escaping special characters
escaped = "This is a line break:\nNext line starts here."
print("\nEscaping Example:\n", escaped)
# Raw strings (ignore escape sequences)
raw = r"This is a raw string:\nNo new line"
print("Raw String Example:", raw)