You need to sign up to get access!

Sign up to get full access to this course.

A variable is an symbolic name that references a Python object. In this lesson, you will learn about string variables. Feel free to practice with the Python console below:

We can assign a string to a variable like so:

x = "My first variable"
print(x)

Multiline Variables

We can add \n to indicate a new line:

x = "My first variable... \nthis is a new line" 
print(x)

Or we can specify them like so:

x = """
This is a multiline string.
You can have multiple
lines just like this!
"""
print(x)

String Length

When working with strings, it is common to need to limit the length of a string.

x = "My first variable... \nthis is a new line"
len(x)

Strings are arrays!

You can access an index of any string just like an array. The example below will print the first character of the string:

x="This is my string"
print(x[0])

This would be useful if for example if you wanted to do something like take the first and last name of a person and create a username:

firstname = "Joe"
lastname = "Friday"
print(firstname[0] + lastname)

Search Strings

Return true or false if a string contains a keyword:

x = "My first variable... \nthis is a new line"
"variable" in x

We can us if / in to search a string for a keyword:

x = "My first variable... \nthis is a new line"
if "variable" in x:
    print("We found 'variable' in the string!")

Sign up to access the rest of this lesson

You must either log in or sign up to access this lesson.

0 0 votes
Lesson Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments