Python for AIPython for AI
Data Types

Strings

Working with text in Python

In Python, strings are fundamental for handling text. They allow us to store names, messages, and any other sequence of characters.

What are strings?

Think of a string as a series of characters, like letters, numbers, or symbols, all joined together in a specific order. We use them for pretty much anything that involves words or text.

In Python, strings are a type of data, just like numbers. They have their own special ways of working.

Creating strings

You create a string by putting characters inside quotation marks. You can use either single quotes (') or double quotes ("). Python treats them the same.

python
name = "Alice"
message = 'Hello world!'
print(name)
print(message)
It's good practice to be consistent. Pick one type of quote (single or double) and stick with it throughout your code, unless you have a good reason not to.

Combining strings

You can stick strings together, a process called concatenation, using the + operator. It's like adding them up, but for text.

python
greeting = "Hi" + " " + "there!"
name = "Bob"
full_message = greeting + " My name is " + name + "."
print(full_message)

String length

Sometimes you need to know how many characters are in a string. The built-in len() function does just that.

python
word = "Python"
count = len(word)
print(count)

sentence = "This is a sentence."
print(len(sentence))

Converting to string

What if you have a number but you need it as text? You can convert other data types into strings using the str() function.

python
age = 30
age_as_string = str(age)
print(type(age))
print(type(age_as_string))

# Now you can combine it with other strings
message = "My age is " + age_as_string + "."
print(message)

Common mistakes

Here are a couple of things beginners often run into:

  • Forgetting to close quotes: Every opening quote needs a closing one.
  • Trying to combine numbers and strings directly: Remember to use str() to convert numbers first if you're using +.
python
# This causes an error!
# print("Hello " + 5)

# Do this instead:
print("Hello " + str(5))

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
What is `"py" + "thon"`?
Fill in the blanks
Not started
Print the word in lowercase.
1word = "PYTHON"
2

What's next?

Now that you understand the basics of strings, you're ready to start building simple text-based programs. Next, we'll look at how to get input from a user, which often involves working with strings.