Piyush Ranjan
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Introduction description: duration: 200 card_type: cue_card --- # **Strings 2 (2 hours)** [Class Recording](https://www.scaler.com/meetings/i/beginner-strings-2-13/archive) [Lecture Notes](https://scaler-production-new.s3.ap-southeast-1.amazonaws.com/attachments/attachments/000/015/558/original/Strings_2.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIDNNIRGHAQUQRWYA%2F20221205%2Fap-southeast-1%2Fs3%2Faws4_request&X-Amz-Date=20221205T044912Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=60169527e2359ff6276313309b10c3fa89ddd93838cb637c599959cddf38c7ea) [Old Script](https://colab.research.google.com/drive/12GS8NQuNbxDrMQoDd4IdLxWZ-GQWOXYz?usp=sharing) ## **Content** 1. Various String methods. 2. Concept of Mutability and Immutability ### Meanwhile when people are joining (5-7 mins) * Instructor's welcome. * Breaking ice with students. * Casual conversation to bond. --- title: Quiz-1 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" i = 0 while i < len(message): if i % 2 == 0: print(message[i], end = "") i += 1 ``` # Choices - [x] HloWrd - [ ] Hlo ol - [ ] eolWrd - [ ] el or --- title: String Methods description: duration: 2400 card_type: cue_card --- ## String Methods ### .split() method * The str.split() function converts a string into a list of characters based on a splitting criteria. Code: ```python= "4 5 6 7 8 9".split() ``` >Output: ``` ['4', '5', '6', '7', '8', '9'] ``` Code: ```python= "This_is_a_underscore_separated_string".split("_") ``` >Output: ``` ['This', 'is', 'a', 'underscore', 'separated', 'string'] ``` ### .join() method * Opposite of splitting is joining. * We can use str.join() to do so. Code: ```python= random = "This_is_a_underscore_separated_string".split("_") " ".join(random) ``` >Output: ``` 'This is a underscore separated string' ``` Code: ```python= "-".join(random) ``` >Output: ``` 'This-is-a-underscore-separated-string' ``` * While providing an iterable to .join() you need to make sure that the contents of that iterable only contain strings. Else it will throw an error. Code: ```python= # Error a = ["random", 102, 282, "string"] " ".join(a) ``` >Output: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-6c67814fded6> in <module> 1 a = ["random", 102, 282, "string"] ----> 2 " ".join(a) TypeError: sequence item 1: expected str instance, int found ``` ### str() function * We can use str() function to convert numbers to string. Code: ```python= str(45) ``` >Output: ``` '45' ``` ### .find() method * The .find() method can be used to find a substring inside a string that we can call it on. * This function returns the starting index of the first occourance of the substring that we are trying to find inside the string. Code: ```python= "this is a random string".find("is") ``` >Output: ``` 2 ``` * Returns -1 if the substring is not present. Code: ```python= "this is a random string".find("adadsaf") ``` >Output: ``` -1 ``` ### .replace() method * The method .replace() can be used to replace a substring from the original string with the input we provide. * This method takes in two arguments, first the substring from the original string and second the string we want to replace it with. * It replaces the string we provide and returns a new string. Code: ```python= random = "This is a random string that I have created" # The orginal string is not updated. random.replace("random", "SUPER RANDOM") ``` >Output: ``` 'This is a SUPER RANDOM string that I have created' ``` ### .count() method * The method .count() can be used to count the number of occourances of a substring we provide inside a particular string. Code: ```python= random = "This is a random string that I have created" random.count("a") ``` >Output: ``` 5 ``` Code: ```python= random = "This is a random string that I have created random random random" random.count("random") ``` >Output: ``` 4 ``` --- title: Question-1 description: duration: 480 card_type: cue_card --- * Take a string as input. * Convert the string to lowercase without using any inbuilt function. Code: ```python= def custom_lower(s): result = "" for i in s: if ord(i) >= 65 and ord(i) <= 90: order = ord(i) order = order + 32 result = result + chr(order) else: result = result + i return result custom_lower("This is A stRIng") ``` >Output: ``` 'this is a string' ``` --- title: Quiz-2 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.lower()) ``` # Choices - [ ] HELLO WORLD! - [x] hello world! - [ ] hELLO wORLD! - [ ] Hello World! --- title: Quiz-3 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.replace("o", "e")) ``` # Choices - [ ] Helle Welle - [ ] Helle Welle! - [x] Helle Werld! - [ ] Hllo Wrld! --- title: Some more methods description: duration: 1800 card_type: cue_card --- ## Some more methods - ### .isdigit() * .isdigit() returns True a character inside a string is a digit. * This method works only for integers. Code: ```python= "6".isdigit() ``` >Output: ``` True ``` Code: ```python= "a".isdigit() ``` >Output: ``` False ``` Code: ```python: "aasda231321".isdigit() ``` >Output: ``` False ``` Code: ```python= "124143222".isdigit() ``` >Output: ``` True ``` ### .isalpha() * isalpha() returns True if a certain string only contains alphabets Code: ```python= "aasda231321".isalpha() ``` >Output: ``` False ``` Code: ```python= "a".isalpha() ``` >Output: ``` True ``` Code: ```python= "abc".isalpha() ``` >Output: ``` True ``` ### .isupper() and .islower() Code: ```python= "A".isupper() ``` Output: ``` True ``` Code: ```python= "a".isupper() ``` Output: ``` False ``` Code: ```python= "a".islower() ``` Output: ``` True ``` Code: ```python= "A".islower() ``` Output: ``` False ``` ### .isspace() * Returns True if there is a space in the string. Code: ```python= "abc".isspace() ``` >Output: ``` False ``` Code: ```python= " ".isspace() ``` >Output: ``` True ``` --- title: Question-2 description: duration: 400 card_type: cue_card --- * Take a string as input. * Replace all the space with underscore. Code: ```python= string = "this is a random string" # 1 def change_to_underscore(s): result = "" for i in s: if i.isspace(): result = result + "_" else: result = result + i return result change_to_underscore(string) ``` >Output: ``` 'this_is_a_random_string' ``` Code: ```python= # 2 string.replace(" ", "_") ``` >Output: ``` this_is_a_random_string ``` --- title: Quiz-4 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Not Hello World!" print(message.startswith("Hello")) ``` # Choices - [ ] True - [x] False - [ ] None - [ ] Error --- title: Quiz-5 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.find("o")) ``` # Choices - [ ] 8 - [ ] 7 - [x] 4 - [ ] -1 --- title: Glossary of string methods description: duration: 90 card_type: cue_card --- ### Glossary of string methods - <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/775/original/glossary_of_str_methods.png?1689241237" width=600 height=350> --- title: Mutability and Immutability description: duration: 900 card_type: cue_card --- ### Mutability and Immutability Mutable: whose value can change. Immutable: whose value can't change. <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/776/original/mutable_and_immutable_explaination.png?1689241538" width=600 height=150> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/777/original/mutable_and_immutable_explaination_2.png?1689241570" width=600 height=350> Code: ```python= a = 3 a ``` >Output: ``` 3 ``` Code: ```python= a = 4 a ``` >Output: ``` 4 ``` It seems that integers are mutable but NO. originally in python we are just changing the memory reference of a to point to 4 instead of changing its value to 4. Only 3 data types in python are mutable * list * sets * dictionaries Other data types such as strings and tuples(you are going to learn in upcoming lectures) are immutable. > id() function in python gives the memory address of the variable where it is stored Code: ```python= id(a) ``` >Output: ``` 140424322138448 ``` Code: ```python= a = 6 id(a) # it can be seen that memory address is change hence now a is pointing to somewhere else in memory ``` >Output: ``` 140424322138512 ``` Code: ```python= my_list =["Python", "C++", "Java"] id(my_list) ``` >Output: ``` 140423632449408 ``` Code: ```python= my_list.append("HTML") my_list[0] = "Python 3.5" print(my_list) print(id(my_list)) ``` >Output: ``` ['Python 3.5', 'C++', 'Java', 'HTML', 'HTML'] 140423632449408 ``` As lists are mutable, we can see that the same list created in the first cell is modified and the values are changed in the same memory location. Code: ```python= my_string = "Scaled" my_string[5] = "r" # Trying to change the character in the last index print(my_string) ``` >Output: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-5b191cb176fc> in <cell line: 2>() 1 my_string = "Scaled" ----> 2 my_string[5] = "r" # Trying to change the character in the last index 3 print(my_string) TypeError: 'str' object does not support item assignment ``` * We receive an error as strings are immutable and we cannot change the value in place. * We can instead assign a new value to the same variable, which leads to the creation of a different memory space Code: ```python= print(id(my_string)) ``` >Output: ``` 140423625872112 ``` Code: ```python= my_string = "Scaler" print(id(my_string)) ``` >Output: ``` 140423066082608 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully