Skip to Content
Nextra 4.0 is released 🎉

Strings

What are Strings?

A string is simply a sequence of characters enclosed within quotes. These are all strings:

"Hello, World!" 'A' "12345" 'These are Special characters: !@#$%^&*()'

You can use either single quotes (') or double quotes (") to create a string in Python. Just make sure to use the same type of quote at the beginning and end of the string.

Creating String Variables

You can create a string variable just like any other variable. Here’s an example:

# Example of a string variable greeting = "Hello, World!"

Anything enclosed in quotes is considered a string, even if it looks like a number. For example, "12345" is a string, not a number.

Operations with Strings

Just like with numeric types, you can perform various operations with strings. Here are some examples:

# Concatenation greeting = "Hello, " name = "Alice" full_greeting = greeting + name # full_greeting will be "Hello, Alice" # Repetition laugh = "Ha" laughter = laugh * 3 # laughter will be "HaHaHa" # Accessing Characters word = "Python" first_letter = word[0] # first_letter will be 'P' last_letter = word[-1] # last_letter will be 'n'

You will most often be using concatenation. The other operations are less common but still useful in certain situations.

Last updated on