What are String Operations?

  • String Operations allow us to manipulate and work with text-based data
  • NEED to know for handling input/output (big in algorithmic coding), formatting, and data processing

Measuring String Length

  • The len() function in Python allows us to find the length of a string
  • Use .length in JavaScript to do this as well
print(len("Hello"))
5
  • Use Case: Determine number of characters in string (eg for validation of password length)

String Case Convertion

  • Uppercase: Convert to uppercase using .upper() in Python
  • Lowercase: Convert to lowercase using .lower() in Python
print("hello".upper())
print("HELLO".lower())
HELLO
hello
  • Use Case: Useful for standardizing text inputs, like making email addresses case-insensitive

String Slicing

  • Through string slicing, we can access a part of the string using indexes
  • Each character in a string gets assigned a index, starting from 0
  • Syntax is [startindex:endindex]
print("Hello World"[0:5])
Hello
  • Use Case: Extract substrings, like the first word from a sentence

Finding Substrings

  • Searches for a substring and returns its position within a overlaying string
  • .find() in Python
print("Hello World".find("World"))
6
  • Use Case: Helpful for parsing text or finding key words

Replacing Substrings

  • Can replace different parts of a string with something else
  • .replace() in Python
print("Hello World".replace("World", "Mihir"))
Hello Mihir
  • Use Case: Useful for replacing specific parts of text without having to re initiate the whole thing again

Splitting Strings

  • Splits a string into a list of substrings based on a delimiter (most commonly a space or comma)
  • .split() in Python
print("apple,banana,grape".split(","))
['apple', 'banana', 'grape']
  • Use Case: Parse through CSV files or processing large lists of items

Joining Strings

  • Basically opposite of splitting strings
  • .join() in Python
print(",".join(['apple', 'banana', 'grape']))
apple,banana,grape
  • Use Case: Combine a list of strings into a single string, helpful for reformatting content