Strings
This page will teach you about strings in programming.
Strings
What are Strings?
- Strings are a data type.
- It is a sequence of characters (letters, numbers, symbols, spaces) enclosed in quotes.
Examples:
myName = "Aneesh"
myNameType = type(myName).__name__
print(f"{myName} is a {myNameType} data type.")
Aneesh is a str data type.
word = "hello" # <-- Here, we use double quotes instead of single quotes
sentence = 'Python is fun!' # <-- Here, we use single quotes instead of double quotes
# Both are valid ways to define strings in Python
multiline = """This is
a multi-line
string.""" # <-- Triple quotes allow for multi-line strings
print(word)
print(sentence)
print(multiline)
hello
Python is fun!
This is
a multi-line
string.
Common String Operations
name = "Aneesh"
print(name.upper()) # "ANEESH"
print(name.lower()) # "aneesh"
print(len(name)) # 6
print(name[0]) # "A" (first character)
print(name[-1]) # "h" (last character)
print(name[1:3]) # "ne" (slice)
ANEESH
aneesh
6
A
h
ne
JavaScript
%%js
let firstName = "Ethan"; // define variables
let lastName = "Patel"; // define variables
console.log(firstName.concat(" ", lastName)); // concat is used in JavaScript to combine strings
let fullName = "Moiz Lukmani"; // define variables
console.log(fullName.substring(0,4)); //substring in JavaScript chooses the letter defined by the index
<IPython.core.display.Javascript object>
Combining Strings
first = "Hello"
second = "World"
print(first + " " + second) # "Hello World"
print(first + ", " + second + "!") # "Hello, World!"
print("{} {}".format(first, second)) # "Hello World" (str.format)
print(f"{first}, {second}!") # "Hello, World!" (f-string)
Hello World
Hello, World!
Hello World
Hello, World!
Popcorn Hacks 1
playerName = "Neil Manjrekar" # <-- Add your own name
# <-- Add a variable called "welcomeMessage" and set the variable equal to "Welcome to the game!"
# Print welcome message
print(welcomeMessage + ", " + playerName + "!")
Popcorn Hacks 2
# Create a game title
gameTitle = "" # <-- Add your favorite game title (ex: "Tic Tac Toe")
# Print the title in uppercase
print(gameTitle.upper()) # <-- What will this display?
# Get the length of the title
titleLength = len(gameTitle)
print("Your game title has " + str(titleLength) + " characters.")
Popcorn Hack 3
%%js
let fullName = "Tanay Paranjpe"; // <-- Add your full name
// Extract first name (characters before the space)
let firstName = fullName.substring(0,100); // <-- Change the numbers to get the first name correctly
// Extract last name (characters after the space)
let lastName = fullName.substring(100); // <-- Change this to get the last name correctly
// Print results
console.log("First: " + firstName);
console.log("Last: " + lastName);
<IPython.core.display.Javascript object>
MCQ
Go as fast as you can to try to win!