Python Logo

String


Strings in Python are sequences of characters. They can be created using single quotes ('), double quotes ("), or triple quotes ("""). For example:

 

Python

my_string = "Hello, World!"
 

Strings can be accessed by their index using the square bracket ([]) operator. For example:

 

Python

print(my_string[0])  # Outputs "H"
 

Strings can also be sliced to get a substring. For example:

 

Python

print(my_string[0:5])  # Outputs "Hello"
 

Strings are immutable, meaning that their contents cannot be changed once they have been created. To change the contents of a string, you must create a new string.

Strings can be concatenated using the + operator. For example:

 

Python

print(my_string + "!"# Outputs "Hello, World!"
 

Strings can also be repeated using the * operator. For example:

 

Python

print(my_string * 3# Outputs "Hello, World!Hello, World!Hello, World!"
 

Strings can be compared using the relational operators (<, >, <=, >=, ==, and !=). For example:

 

Python

print("Hello" < "World!"# Outputs True
 

Strings can also be used in logical expressions using the and, or, and not operators. For example:

 

Python

print("Hello" in my_string)  # Outputs True
 

Strings can be formatted using the format() method. For example:

 

Python

print("My name is {} and I am {} years old.".format("Bard", 1))  # Outputs "My name is Bard and I am 1 years old."
 

Python strings are a powerful tool that can be used for a variety of tasks, such as text processing, web development, and data science.

Here are some additional tips for using strings in Python:

  • Use descriptive variable names for your strings.
  • Add comments to your code to explain what your strings are used for.
  • Use the isinstance() function to check the data type of a variable before using it as a string. This can help you to avoid errors.
  • Use the format() method to format your strings in a consistent way.

I hope this tutorial is helpful. Please let me know if you have any other questions.