Big Idea 3 Unit 4
Oct 11, 2024 • 3 min read
Overview
This unit focused on working with strings and string functions in both Python and JavaScript.
String Methods in Python
upper(): Converts all characters in the string to uppercase.lower(): Converts all characters in the string to lowercase.capitalize(): Capitalizes only the first character.replace(): Substitutes one substring with another.split(): Breaks a string into a list of substrings based on a delimiter.join(): Combines a list of strings into one string with a specified separator.isnumeric(): ReturnsTrueif all characters are digits.
Useful Functions:
len(): Returns the number of characters in a string.str(): Converts any value to a string.- f-strings: Format strings with embedded expressions using curly braces
{}. find(): Finds the lowest index where a substring appears, or -1 if not found.
String Operations in JavaScript
- Concatenation: Combine strings using the
+operator. - Substring: Extract smaller parts from a string.
- length: Get the number of characters in a string.
Python Examples
name_length = len("Kharia")
print(name_length)
full_name = "Kush " + "Kharia"
print(full_name)
substring = full_name[2:6]
print(substring)
```python
def character_count(input_string):
letters = 0
numbers = 0
spaces = 0
for char in input_string:
if char.isalpha():
letters += 1
elif char.isdigit():
numbers += 1
elif char.isspace():
spaces += 1
return letters, numbers, spaces
# Get input from the user
user_input = input("Enter a string: ")
letters, numbers, spaces = character_count(user_input)
print(f"Total letters: {letters}")
print(f"Total numbers: {numbers}")
print(f"Total spaces: {spaces}")
// Length of a string
let lastName = "Kandula";
console.log(lastName.length); // Output: 7
// Concatenate first and last names
let fullName = "Soumini " + "Kandula";
console.log(fullName); // Output: Soumini Kandula
// Extract substring (characters 2 to 8)
let substring = fullName.substring(1, 8);
console.log(substring); // Output: oumini K
function characterCount(inputString) {
let letters = 0;
let numbers = 0;
let spaces = 0;
for (let char of inputString) {
if (/[a-zA-Z]/.test(char)) {
letters++;
} else if (/[0-9]/.test(char)) {
numbers++;
} else if (char === ' ') {
spaces++;
}
}
return [letters, numbers, spaces];
}
const userInput = prompt("Enter a string:");
const [letters, numbers, spaces] = characterCount(userInput);
console.log(`Total letters: ${letters}`);
console.log(`Total numbers: ${numbers}`);
console.log(`Total spaces: ${spaces}`);