Guide to High School Computer Science
  • 💻Introduction
    • windows & Python Development
    • macOS & Python Development
    • Visual Studio Code Settings
    • Set up Github
    • Author Page
  • 🧠Prerequisite Skills
    • Keyboard Typing
    • Files & Directories
    • Use of Command Line
    • Git & GitHub
    • Markdown
    • Starting Your Python Project
  • 🐍Python Programming
    • 🍎Python Basics
      • What is Python?
      • Procedural Programming & Programming Paradigms
      • String Formatting
      • Data Types
      • Input & Output to Console
      • Working with Numbers
      • Useful Built-in Functions
      • Math & Random Module
      • Boolean Data Object
      • Comparison, Logical, and Membership Operators
      • If Statements
      • Binary Decisions
      • Multiple Decisions
      • Nested Conditions
      • [EXTRA] Bitwise Operators
      • [EXTRA] Python Style Guide
    • ⏮️Iterations
      • Introduction to While Loops
      • Infinite Loop
      • Controlling Your While Loops
      • Introduction to For Loops
      • For Loops w/ Numeric Sequences
      • For Loops w/ Strings & Lists
      • Iterable Functions w/ For Loops
    • 📦Collections
      • Strings
        • String Basics
        • String Indexing
        • String Slicing
        • String Operators & Functions
        • Basic String Methods
        • String Methods Extended
        • String Methods Document
      • Tuples & Lists
        • Tuples
        • List Basics
        • List are Mutable
        • Adding Items to a List
        • Removing Items from a List
        • Search & Reverse a List
        • List Comprehension
        • List Methods Document
      • Sets
      • Dictionary
      • How to Store Multiple Data Items
    • 💡Defining Functions
      • Functions
      • print() vs return
      • Pre-determined Arguments
      • Nested Functions
      • Map & Filter
      • [Extra] Dynamic Arguments
    • 💾File I/O
      • How to Save Text to an External File
      • Reading CSV in Python
      • Reading JSON in Python
    • 🔨Basic Python Projects
      • Basic Calculator
        • Improving the calculator
        • Exercise Set 1
        • Exercise Set 2
        • 💎Streamlit Application #1
      • Basic Password Generator
        • Exercise Set 3
        • Exercises Related to Math
        • 💎Streamlit Application #2
      • A To-Do Task List
    • ⏳Introduction to Algorithmic Thinking
      • Big-O Notation
      • Basic Algorithms
        • Linear Search
        • Binary Search
        • Basic Sorting Algorithms
      • Recursion
      • Brute Force Algorithms
      • Greedy Algorithm
        • Time on Task (CCC 2013 J4)
        • Dijkstra’s Algorithm
      • Divide and Conquer
        • Merge Sort
      • Dynamic Programming
    • 🤯Object Oriented Programming
      • Class & Objects (Definitions)
      • OOP in Python
      • Encapsulation
      • Polymorphism
      • Inheritance & Overriding
      • Override Magic Methods
      • Case Study: 2D Vectors
      • Case Study: Deck of Cards
      • Exercise
      • Abstract Data Types
      • Case Study: Static 1D Array From Java
    • Competitive Programming
      • Is This Sum Possible?
        • Is the dataset sorted?
        • Searching for a value
        • Determine if the difference between an integer from the array and the target value exists
        • Sorting Algorithms
        • Using Two Pointers
      • Two Sum - LeetCode
        • Generate all possible pairs of values
        • Subtract each value from the target, see if the difference exists in the list
      • Longest Common Prefix - LeetCode
        • Compare all possible prefixes
        • Create the longest common prefix with the direct neighbour
      • Length of Last Word - LeetCode
        • Compare all possible prefixes
      • Where can I go from one point to another?
      • Sample Outline
    • IB Recipe Book
  • 💾Python & Databases
    • Intro to Databases & Data Modeling
      • Common Data Types in SQL
      • Introduction to ERDs
      • Primary Keys and Foreign Keys
      • Database Normalization
    • What is SQL?
      • Getting Started
      • SELECT Queries
        • Selection with Conditions
        • Selection with Fuzziness
        • Selection and Sorting in Order
        • Selection without Duplicates
        • Selection with Limited Number of Outputs
      • AGGREGATE Queries
        • Counting Rows
        • Sum, Average, Min/Max Queries
        • Working with Aggregate Queries
        • Power of using Groups
        • Exercise
      • Interacting with Multiple Table
      • Inserting Data
      • External Resource
  • ☕Java Essentials
    • Basics
      • Starting Java
      • Data & Variables
      • Handling User Inputs & Type Conversion
      • Arithmetic
      • IPO Model
      • Basic Built-in Methods
      • Exercise Questions
    • Conditionals
      • Boolean Operators
      • Compare Strings
      • If Statements
      • If Else Statements
      • Making Multiple Decisions
      • Using Switch
      • Flowchart Symbols
      • Exercise Questions
    • Iterations
      • While Loops
      • For Loop
      • Exercises
    • Java Type Casting
    • Strings
      • Common String Practices
      • String Formatting
      • Java Special Characters
    • Collection
      • Arrays
      • For Each Loop
      • ArrayList
      • Exercise Questions
    • Static Methods
      • (Aside) Clearing your Console
    • Randomness in Java
    • Delayed Output in Java
    • Java Output Formatting
    • Java Style Guide
  • 🛠️JavaScript Programming
    • Our Programming Editor & Workflow
      • Hello, world!
      • Commenting & Variables
      • Data in JavaScript
      • Operators
      • String Formatting
      • Getting User Input
    • JavaScript Exercise Set 1
    • Making Decisions
      • Comparing Values
      • Combining Boolean Comparisons
      • Creating Branches
    • JavaScript Exercise Set 2
    • While Loops
      • Infinite While Loop
      • While Loops and Numbers
      • While Loops and Flags
      • While loops w/ Strings
    • JavaScript Exercise Set 3
    • Subprograms & Functions
      • Creating a Function in JavaScript
      • Function with Input and Assignable Output
    • JavaScript Exercise Set 4
  • 💾Topics in CS
    • Computer Environments & Systems
      • Computer Components
        • In-depth Explanations
      • File Maintenance
      • Computer & Safety
      • Software Development
      • Bits & Binary
    • Careers related to Computer Science
    • Postsecondary Opportunities
Powered by GitBook
On this page
  1. Python Programming
  2. Collections
  3. Strings

Basic String Methods

PreviousString Operators & FunctionsNextString Methods Extended

Last updated 1 year ago

In this lesson, we will be looking a string methods that deal with searching, checking the status, and editing strings.

This is not an exhaustive list of all methods with strings. You check out the list of methods .

Methods: set of code belonging to a certain data/object

  • String and List data types have special methods only for them

  • Usually, we need a period before the method name to use them

Example:

print('Hello {}!'.format('World'))

.format() is a string method!

Return: certain methods and functions have the ability to return a value/result after its operations

  • This is useful when we assign the result to a variable

  • Built-in functions like: len(), max(), min(), int(), float() all return a new value so that we can assign the result to a variable or update an existing variable

Search Related Methods

Recall: Index starts at 0

string_data.count(_str_arg_)

  • Returns how many time the string argument occurs in the given variable

string_data.find(_str_arg_)

  • Returns the location of where the string argument was found. If not found, returns -1

string_data.index(_str_arg_)

# Search Related Methods Examples

example = 'hello world!'
result_1 = example.count('e') # is 1
result_2 = example.count('l') # (single lowercase L) is 3
result_3 = example.count('ll') # (double lowercase L) is 1
print('result_1:', result_1)
print('result_2:', result_2)
print('result_3:', result_3)
print('-'*64)

result_4 = example.find('d') # is 10 … found at index 10
result_5 = example.find('z') # is -1 … not found
result_6 = example.find('or') # is 7 … ‘or’ begins at index 7
print('result_4:', result_4)
print('result_5:', result_5)
print('result_6:', result_6)
print('-'*64)

result_7 = example.index('d') # is 10 … found at index 10
print('result_7:', result_7)
result_8 = example.index('or') # is 7 … ‘or’ begins at index 7
print('result_8:', result_8)
result_9 = example.index('z') # is an error
print('result_9:', result_9)
print('-'*64)
result_1: 1
result_2: 3
result_3: 1
----------------------------------------------------------------
result_4: 10
result_5: -1
result_6: 7
----------------------------------------------------------------
result_7: 10
result_8: 7



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-11-3bf5d49914e1> in <module>
     22 result_8 = example.index('or') # is 7 … ‘or’ begins at index 7
     23 print('result_8:', result_8)
---> 24 result_9 = example.index('z') # is an error
     25 print('result_9:', result_9)
     26 print('-'*64)


ValueError: substring not found

String Status Methods

These methods will all either return True or False.

string_data.isalnum()

  • Checks iff alpha+numeric, no spaces or no special characters

string_data.isalpha()

  • Checks iff alpha, no spaces, no numbers or no special characters

string_data.islower()

  • Checks iff all characters are lowercased, doesn’t check whitespaces

string_data.isupper()

  • Check iff all characters are uppercased, doesn’t check whitespaces

string_data.isdigit()

  • Checks iff numeric, no spaces or no special characters, ignores unicode majority of the time, this is preferred over .isnumeric() and .isdecimal()

# String Status Methods Example

example1 = 'abc123'
example2 = '123'
example3 = 'HELLO'

print('example1.isalnum():', example1.isalnum()) # outputs True
print('example1.isalpha():', example1.isalpha()) # outputs False

print('example3.islower():', example3.islower()) # outputs False
print('example3.isupper():', example3.isupper()) # outputs True

print('example2.isdigit():', example2.isdigit()) # outputs True
print('example1.isdigit():', example1.isdigit()) # outputs False
example1.isalnum(): True
example1.isalpha(): False
example3.islower(): False
example3.isupper(): True
example2.isdigit(): True
example1.isdigit(): False

String Editing Methods

These methods will return a new string

string_data.capitalize()

  • Capitalizes the first letter of a string

string_data.lower()

  • Returns with all characters in the string lowercased

string_data.upper()

  • Returns with all characters in the string uppercased

# Editing Strings Example
# string variables must be updated with new values if you want to modify it

example = 'hello, world!'
example = example.capitalize() # example : ‘Hello, world!’
print('example:', example)

example = example.upper() # example : ‘HELLO, WORLD!’
print('example:', example)

example = example.lower() # example : ‘hello, world!’
print('example:', example)
example: Hello, world!
example: HELLO, WORLD!
example: hello, world!

Same as find(), but raises an if str not found.

🐍
📦
here
exception