CBSERanker

Loading

notes on Strings in Python

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

  1. 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"
  1. Repetition: Repeating a string multiple times using the * operator.
  • Example from PDF:
    python Line = "go" print(Line * 3, "Govinda") # Output: "gogogo Govinda"
  1. Membership: Using in and not 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
  1. 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

  1. len(): Returns the number of characters in the string, including spaces.
   len("Python")  # Output: 6
  1. capitalize(): Converts the first character of the string to uppercase.
  • Example from PDF:
    python "python".capitalize() # Output: "Python"
  1. title(): Converts the first character of each word to uppercase.
   "hello world".title()  # Output: "Hello World"
  1. lower(): Converts all characters to lowercase.
   "HELLO".lower()  # Output: "hello"
  1. upper(): Converts all characters to uppercase.
   "hello".upper()  # Output: "HELLO"
  1. count(substring): Counts occurrences of a substring within the string.
  • Example from PDF:
    python "banana".count("a") # Output: 3
  1. 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
  1. index(substring): Similar to find(), but raises an error if the substring is not found.
  • Example from PDF:
    python "hello".index("e") # Output: 1
  1. endswith(suffix): Checks if the string ends with the given suffix.
   "hello".endswith("lo")  # Output: True
  1. startswith(prefix): Checks if the string starts with the given prefix. "hello".startswith("he") # Output: True
  2. isalnum(): Checks if the string contains only alphanumeric characters. "abc123".isalnum() # Output: True
  3. isalpha(): Checks if the string contains only alphabetic characters. "abc".isalpha() # Output: True
  4. isdigit(): Checks if the string contains only digits. "123".isdigit() # Output: True
  5. islower(): Checks if all alphabetic characters are lowercase. "hello".islower() # Output: True
  6. isupper(): Checks if all alphabetic characters are uppercase. "HELLO".isupper() # Output: True
  7. isspace(): Checks if the string contains only whitespace. " ".isspace() # Output: True
  8. lstrip(): Removes leading whitespace from the string. " hello".lstrip() # Output: "hello"
  9. rstrip(): Removes trailing whitespace from the string. "hello ".rstrip() # Output: "hello"
  10. strip(): Removes leading and trailing whitespace. " hello ".strip() # Output: "hello"
  11. replace(old, new): Replaces occurrences of old with new.
    • Example from PDF:
    "hello world".replace("world", "Python") # Output: "hello Python"
  12. 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"
  13. 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')
  14. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *