Strings

A string is a sequence of characters. It is used to represent text and is one of the most commonly used data types in Python.

To create a string, you enclose the text in either single quotes (') or double quotes ("). Here's an example:

message = "Hello, world!"
print(message)  # Output: "Hello, world!"

In this example, we created a string called message that contains the text "Hello, world!". The quotes are used to indicate that the content is a string.

You can access individual characters in a string by their index, similar to how you access items in a list. The index starts from 0 for the first character, 1 for the second character, and so on. For example:

print(message[0])  # Output: "H"
print(message[7])  # Output: "w"

In this code, we use square brackets after the string name to access specific characters. message[0] gives us the first character in the string, which is "H", and message[7] gives us the eighth character, which is "w".

You can also use various string methods to manipulate and work with strings. For example:

print(len(message))  # Output: 13 (length of the string)

print(message.upper())  # Output: "HELLO, WORLD!" (converts to uppercase)

print(message.replace("Hello", "Hi"))  # Output: "Hi, world!" (replaces a substring)

print(message.split(","))  # Output: ["Hello", " world!"] (splits the string into a list)

In this code, we use the len() function to get the length of the string, the upper() method to convert the string to uppercase, the replace() method to replace a substring within the string, and the split() method to split the string into a list based on a delimiter (in this case, a comma).

Strings in Python are immutable, which means you cannot change individual characters within a string.

message = "Hello?"
print(message[0])  # Outputs: H
message[0] = "J"   # This results in an error

However, you can create new strings by concatenating or combining existing strings. Here's an example:

greeting = "Hello"
name = "John"
message = greeting + " " + name
print(message)  # Output: "Hello John"

In this code, we use the + operator to concatenate the strings greeting, a space, and name into a new string called message.

Combining variables into strings as in the example above is much easier if we make use of f-strings.

These are just a few basic operations you can perform with strings in Python. There are many more methods and functionalities available for working with strings, such as searching for substrings, formatting, and more. Refer to the offical Python documentation on strings to learn more.