Intro to Python
Share
Explore
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 , 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)
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
Search
Task
Status
1
Learn how to use strings
Not Started
No results from filter

Next Section ➡️

Share
 
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.