notes on Strings in Python
Here’s the enriched class note with more detailed explanations and examples based on the content from your PDF:
Strings: Introduction
- A string is a sequence of characters enclosed within single (
'...'
), double ("..."
), or triple quotes ('''...'''
or"""..."""
). - Strings are immutable, meaning once a string is created, it cannot be changed.
- Examples:
string1 = "Hello, World!"
string2 = 'Python Programming'
string3 = '''This is a
multiline string'''
String Operations
- Concatenation: Joining two or more strings using the
+
operator.
- Example from PDF:
python A = "Tom" B = "Jerry" C = A + " & " + B print(C) # Output: "Tom & Jerry"
- Repetition: Repeating a string multiple times using the
*
operator.
- Example from PDF:
python Line = "go" print(Line * 3, "Govinda") # Output: "gogogo Govinda"
- Membership: Using
in
andnot in
operators to check if a substring exists.
- Example from PDF:
python 'a' in 'python' # Output: False 'a' in 'java' # Output: True 'per' in 'operators' # Output: True
- Slicing: Extracting parts of a string using slice notation.
- Example from PDF:
python str1 = "wonderful" print(str1[0:6]) # Output: "wonder" print(str1[0::2]) # Output: "wnefl" print(str1[::-1]) # Output: "lufrednow" (reverse string)
Traversing a String Using Loops
- Traversing means accessing each character of the string one by one.
- Example from PDF:
name = "lovely"
for ch in name:
print(ch, '-', end='') # Output: l-o-v-e-l-y-
Built-in String Functions/Methods
len()
: Returns the number of characters in the string, including spaces.
len("Python") # Output: 6
capitalize()
: Converts the first character of the string to uppercase.
- Example from PDF:
python "python".capitalize() # Output: "Python"
title()
: Converts the first character of each word to uppercase.
"hello world".title() # Output: "Hello World"
lower()
: Converts all characters to lowercase.
"HELLO".lower() # Output: "hello"
upper()
: Converts all characters to uppercase.
"hello".upper() # Output: "HELLO"
count(substring)
: Counts occurrences of a substring within the string.
- Example from PDF:
python "banana".count("a") # Output: 3
find(substring)
: Returns the index of the first occurrence of the substring, or-1
if not found.
- Example from PDF:
python "hello".find("e") # Output: 1
index(substring)
: Similar tofind()
, but raises an error if the substring is not found.
- Example from PDF:
python "hello".index("e") # Output: 1
endswith(suffix)
: Checks if the string ends with the given suffix.
"hello".endswith("lo") # Output: True
startswith(prefix)
: Checks if the string starts with the given prefix."hello".startswith("he") # Output: True
isalnum()
: Checks if the string contains only alphanumeric characters."abc123".isalnum() # Output: True
isalpha()
: Checks if the string contains only alphabetic characters."abc".isalpha() # Output: True
isdigit()
: Checks if the string contains only digits."123".isdigit() # Output: True
islower()
: Checks if all alphabetic characters are lowercase."hello".islower() # Output: True
isupper()
: Checks if all alphabetic characters are uppercase."HELLO".isupper() # Output: True
isspace()
: Checks if the string contains only whitespace." ".isspace() # Output: True
lstrip()
: Removes leading whitespace from the string." hello".lstrip() # Output: "hello"
rstrip()
: Removes trailing whitespace from the string."hello ".rstrip() # Output: "hello"
strip()
: Removes leading and trailing whitespace." hello ".strip() # Output: "hello"
replace(old, new)
: Replaces occurrences ofold
withnew
.- Example from PDF:
"hello world".replace("world", "Python") # Output: "hello Python"
join(iterable)
: Joins elements of an iterable (e.g., list) into a string, separated by a specified delimiter."-".join(["a", "b", "c"]) # Output: "a-b-c"
partition(sep)
: Splits the string into three parts: before the separator, the separator itself, and after the separator.- Example from PDF:
"apple#banana#cherry".partition("#") # Output: ('apple', '#', 'banana#cherry')
split(sep)
: Splits the string at the specified delimiter and returns a list of parts.python "apple,banana,cherry".split(",") # Output: ['apple', 'banana', 'cherry']
Additional Examples from PDF:
- Reversing a String:
string1 = "karan"
length = len(string1)
for ch in range(-1, -length-1, -1):
print(string1[ch])
# Output: n a r a k
- Program to Count Vowels:
string = input("Enter a string: ")
vowels = 'aeiouAEIOU'
count = 0
for ch in string:
if ch in vowels:
count += 1
print("Number of vowels:", count)
These enriched notes provide more detailed examples and descriptions from the PDF, making the content more engaging and practical for students.