Tuesday, December 24, 2024

Python Strings Definition Quotes Assigning String Slicing Methods Escape Characters Format Concatenation

💥 WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka

Points on Python Strings

  1. Definition of Strings

    • Strings in Python are surrounded by either single (') or double (") quotation marks.
      Example:
      print("Hello")
      print('Hello')
      
  2. Quotes Inside Strings

    • Quotes inside strings can be used as long as they don't match the outer quotes.
      Example:
      print("It's alright")
      print("He is called 'Johnny'")
      print('He is called "Johnny"')
      
  3. Assigning Strings to Variables

    • Strings can be assigned to variables using the equal sign (=).
      Example:
      a = "Hello"
      print(a)
      
  4. Multiline Strings

    • Multiline strings are created using triple quotes (""" or ''').
      Example:
      a = """Lorem ipsum dolor sit amet,
      consectetur adipiscing elit."""
      print(a)
      
      Or:
      a = '''Lorem ipsum dolor sit amet,
      consectetur adipiscing elit.'''
      print(a)
      
  5. Strings as Arrays

    • Strings are arrays of bytes representing Unicode characters.
    • Access elements using square brackets ([]).
      Example:
      a = "Hello, World!"
      print(a[1])  # Outputs 'e'
      
  6. Looping Through a String

    • Strings can be iterated using a for loop.
      Example:
      for x in "banana":
          print(x)
      
  7. String Length

    • Use the len() function to get the length of a string.
      Example:
      a = "Hello, World!"
      print(len(a))  # Outputs 13
      
  8. Check String Presence

    • Use the in keyword to check if a substring is present.
      Example:
      txt = "The best things in life are free!"
      print("free" in txt)  # Outputs True
      
    • Use in with an if statement:
      if "free" in txt:
          print("Yes, 'free' is present.")
      
  9. Check String Absence

    • Use the not in keyword to check if a substring is not present.
      Example:
      txt = "The best things in life are free!"
      print("expensive" not in txt)  # Outputs True
      
    • Use not in with an if statement:
      if "expensive" not in txt:
          print("No, 'expensive' is NOT present.")
      
  10. Exercise

    • Question:
      x = 'Welcome'
      print(x[3])
      
    • Answer: The output will be:
      c (since indexing starts at 0).
  1. Slicing Syntax

    • Strings can be sliced using the syntax [start:end].
    • The slicing returns characters from the start index up to, but not including, the end index.
      Example:
      b = "Hello, World!"
      print(b[2:5])  # Outputs 'llo'
      
    • Note: Indexing starts at 0.
  2. Slice From the Start

    • Omitting the start index makes the slice begin from the start of the string.
      Example:
      b = "Hello, World!"
      print(b[:5])  # Outputs 'Hello'
      
  3. Slice To the End

    • Omitting the end index makes the slice go until the end of the string.
      Example:
      b = "Hello, World!"
      print(b[2:])  # Outputs 'llo, World!'
      
  4. Negative Indexing

    • Negative indices count from the end of the string.
    • Example:
      b = "Hello, World!"
      print(b[-5:-2])  # Outputs 'orl'
      
      • Here, -5 corresponds to "o" in "World!" and -2 excludes "d" in "World!".
  5. Exercise

    • Question:
      x = 'Welcome'
      print(x[3:5])
      
    • Answer: The output will be:
      co (characters from index 3 to 4, as index 5 is not included).

Points on Python - Modify Strings

  1. Built-in Methods

    • Python provides built-in methods to modify strings.
  2. Convert to Upper Case

    • The upper() method converts all characters in the string to upper case.
      Example:
      a = "Hello, World!"
      print(a.upper())  # Outputs: "HELLO, WORLD!"
      
  3. Convert to Lower Case

    • The lower() method converts all characters in the string to lower case.
      Example:
      a = "Hello, World!"
      print(a.lower())  # Outputs: "hello, world!"
      
  4. Remove Whitespace

    • The strip() method removes whitespace from the beginning and the end of the string.
      Example:
      a = " Hello, World! "
      print(a.strip())  # Outputs: "Hello, World!"
      
  5. Replace Substring

    • The replace() method replaces a specified substring with another substring.
      Example:
      a = "Hello, World!"
      print(a.replace("H", "J"))  # Outputs: "Jello, World!"
      
  6. Split String

    • The split() method splits the string into substrings based on a specified separator and returns them as a list.
      Example:
      a = "Hello, World!"
      print(a.split(","))  # Outputs: ['Hello', ' World!']
      
  7. String Methods Reference

    • Python provides many more string methods. Refer to Python's String Methods Reference for a complete list.
  8. Exercise

    • Question:
      What is the correct syntax to print a string in upper case letters?
      • 'Welcome'.upper()
      • 'Welcome'.toUpper()
      • 'Welcome'.toUpperCase()
    • Correct Answer:
      'Welcome'.upper()


String Concatenation

  1. String Concatenation

    • Concatenation is the process of combining two or more strings.
  2. Using the + Operator

    • The + operator can be used to concatenate strings.
      Example:
      a = "Hello"
      b = "World"
      c = a + b
      print(c)  # Outputs: "HelloWorld"
      
  3. Adding a Space Between Strings

    • To include a space between concatenated strings, add " " in between.
      Example:
      a = "Hello"
      b = "World"
      c = a + " " + b
      print(c)  # Outputs: "Hello World"
      
  4. Exercise

    • Question:
      What is the correct syntax to merge variable x and y into variable z?
      • z = x, y
      • z = x = y
      • z = x + y
    • Correct Answer:
      z = x + y

Format Strings

  1. String Format Problem

    • Strings and numbers cannot be combined directly using +.
      Example:
      age = 36
      txt = "My name is John, I am " + age  # ❌ Results in an error
      print(txt)
      
  2. Solutions for Combining Strings and Numbers

    • Use f-strings or the format() method.
  3. F-Strings

    • Introduced in Python 3.6 and is the preferred method for string formatting.
    • Add an f before the string and use {} as placeholders.
      Example:
      age = 36
      txt = f"My name is John, I am {age}"
      print(txt)  # Outputs: "My name is John, I am 36"
      
  4. Placeholders and Modifiers

    • Placeholders in f-strings can include variables, operations, and modifiers.
  5. Placeholders for Variables

    • Example:
      price = 59
      txt = f"The price is {price} dollars"
      print(txt)  # Outputs: "The price is 59 dollars"
      
  6. Using Modifiers in Placeholders

    • A modifier formats the value inside a placeholder.
    • Example with .2f (fixed-point number with 2 decimals):
      price = 59
      txt = f"The price is {price:.2f} dollars"
      print(txt)  # Outputs: "The price is 59.00 dollars"
      
  7. Performing Math Operations in Placeholders

    • Example:
      txt = f"The price is {20 * 59} dollars"
      print(txt)  # Outputs: "The price is 1180 dollars"
      
  8. Exercise

    • Question: If x = 9, what is the correct syntax to print "The price is 9.00 dollars"?
      • print(f'The price is {x:.2f} dollars')
      • print(f'The price is {x:2} dollars')
      • print(f'The price is {x:format(2)} dollars')
    • Correct Answer:
      print(f'The price is {x:.2f} dollars')  # Outputs: "The price is 9.00 dollars"
      

***

Escape Characters in Python

  1. Purpose of Escape Characters

    • Escape characters allow the insertion of characters that are illegal or problematic in a string.
    • They are written as a backslash \ followed by the character to insert.
  2. Example of Illegal Character

    • Using double quotes inside a string surrounded by double quotes results in an error:
      txt = "We are the so-called "Vikings" from the north."  # ❌ Error
      
  3. Fixing the Problem with Escape Characters

    • Use \" to include double quotes in a string:
      txt = "We are the so-called \"Vikings\" from the north."
      print(txt)  # Outputs: We are the so-called "Vikings" from the north.
      
  4. List of Escape Characters

    • \': Inserts a single quote.
      Example:

      txt = 'It\'s a sunny day.'
      print(txt)  # Outputs: It's a sunny day.
      
    • \\: Inserts a backslash.
      Example:

      txt = "This is a backslash: \\"
      print(txt)  # Outputs: This is a backslash: \
      
    • \n: Inserts a new line.
      Example:

      txt = "Hello\nWorld!"
      print(txt)  
      # Outputs:
      # Hello
      # World!
      
    • \r: Inserts a carriage return.
      Example:

      txt = "Hello\rWorld"
      print(txt)  # Outputs: World (carriage return overwrites the line)
      
    • \t: Inserts a tab.
      Example:

      txt = "Hello\tWorld"
      print(txt)  # Outputs: Hello    World
      
    • \b: Inserts a backspace.
      Example:

      txt = "Hello\bWorld"
      print(txt)  # Outputs: HellWorld (removes 'o')
      
    • \f: Inserts a form feed.
      Example:

      txt = "Hello\fWorld"
      print(txt)  # Outputs: HelloWorld (new page indicator)
      
    • \ooo: Inserts a character based on its octal value.
      Example:

      txt = "\110\145\154\154\157"  # Octal for 'Hello'
      print(txt)  # Outputs: Hello
      
    • \xhh: Inserts a character based on its hex value.
      Example:

      txt = "\x48\x65\x6C\x6C\x6F"  # Hex for 'Hello'
      print(txt)  # Outputs: Hello
      

 String Methods

  1. General Note

    • All string methods return new values and do not change the original string.
  2. String Methods and Their Descriptions

Method Description
capitalize() Converts the first character to upper case.
casefold() Converts string into lower case (more aggressive than lower()).
center() Returns a centered string.
count() Returns the number of times a specified value occurs in a string.
encode() Returns an encoded version of the string.
endswith() Returns True if the string ends with the specified value.
expandtabs() Sets the tab size of the string.
find() Searches for a specified value and returns the position where it was found.
format() Formats specified values in a string.
format_map() Formats specified values in a string using a dictionary.
index() Searches for a specified value and returns its position (raises an error if not found).
isalnum() Returns True if all characters in the string are alphanumeric.
isalpha() Returns True if all characters in the string are alphabetic.
isascii() Returns True if all characters in the string are ASCII characters.
isdecimal() Returns True if all characters in the string are decimals.
isdigit() Returns True if all characters in the string are digits.
isidentifier() Returns True if the string is a valid identifier.
islower() Returns True if all characters in the string are lower case.
isnumeric() Returns True if all characters in the string are numeric.
isprintable() Returns True if all characters in the string are printable.
isspace() Returns True if all characters in the string are whitespaces.
istitle() Returns True if the string follows title case rules.
isupper() Returns True if all characters in the string are upper case.
join() Joins the elements of an iterable to the string.
ljust() Returns a left-justified version of the string.
lower() Converts a string to lower case.
lstrip() Returns a left-trimmed version of the string.
maketrans() Returns a translation table for use in string translation.
partition() Splits the string into three parts: before, the separator, and after.
replace() Replaces a specified value with another value in the string.
rfind() Searches for a specified value and returns the last position of where it was found.
rindex() Searches for a specified value and returns its last position (raises an error if not found).
rjust() Returns a right-justified version of the string.
rpartition() Splits the string into three parts from the right: before, the separator, and after.
rsplit() Splits the string at the specified separator from the right and returns a list.
rstrip() Returns a right-trimmed version of the string.
split() Splits the string at the specified separator and returns a list.
splitlines() Splits the string at line breaks and returns a list.
startswith() Returns True if the string starts with the specified value.
strip() Returns a trimmed version of the string (removes spaces from both ends).
swapcase() Swaps case: lower case becomes upper case, and vice versa.
title() Converts the first character of each word to upper case.
translate() Returns a translated string using a translation table.
upper() Converts a string to upper case.
zfill() Pads the string with zeros on the left until it reaches the specified length.










No comments:

Post a Comment