JavaScript required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Gallery
Intro to Python
Share
Explore
Gallery
Intro to Python
Introduction
Learn Python
What is a program?
Variables, Expressions, and Statements
Conditionals
Functions
Lists, Sets, and Dictionaries
Loops
Strings
Guess the Word
Summary
Resources
Help
Data
Learn Python
Strings
This section covers:
Finding the length of strings
String concatenation
Strings and looping
Using the
in
operator
As you may recall from
Variables, Expressions, and Statements
, strings are sequences of letters surrounded by double or single quotes.
In Python, we generally use single quotes unless the string contains an apostrophe.
example_string =
'this is a string!'
another_example_string =
"isn't this cool?"
Like with lists, you can access characters in the string using index notation. Remember that the first character is at index 0.
example_string =
'this is a string!'
second_character = example_string[1]
# second_character is 'h'
Finding the length of strings
Like with lists, you can get the length of a string by using
len
.
example_string =
'this is a string!'
length_of_string =
len
(example_string)
# length_of_string is 17
String concatenation
You can also concatenate strings using the
+
operator.
first_name =
'Michelle'
last_name =
'Obama'
full_name = first_name + " " + last_name
# full_name is 'Michelle Obama'
Using loops with strings
Because strings are sequences of characters, you can use a
for
loop to iterate through each character in the string.
The following code snippet will print each character in the string.
example_string =
'this is a string!'
for
ch
in
example_string:
print(ch)
View code on Python Tutor
Checking values in a string
Like with lists, you can check if a given character is in a list using the
in
operator.
example_string =
'this is a string!'
print(
'h'
in example_string)
# prints True
print(
'z'
in example_string)
# prints False
Task
Status
Task
Status
1
Learn how to use strings
Not Started
No results from filter
Next Section ➡️
Guess the Word
Finding the length of strings
String concatenation
Using loops with strings
Checking values in a string
Next Section ➡️ Guess the Word
Gallery
Share
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.