Strings in Python

In Python, a string is a sequence of characters enclosed within quotation marks. Strings are a fundamental data type in Python and can be used to store and manipulate textual data.

Here are some examples of strings in Python:

  1. Declaring a string variable:
my_string = "Hello, world!"
print(my_string)  # Output: "Hello, world!"
  1. Accessing characters in a string using indexing:
my_string = "Hello, world!"
print(my_string[0])  # Output: "H"
print(my_string[7])  # Output: "w"
  1. Slicing a string to extract a substring:
my_string = "Hello, world!"
print(my_string[0:5])  # Output: "Hello"
  1. Concatenating strings:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Output: "John Doe"
  1. Formatting strings using placeholders:
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: "My name is John and I am 25 years old."
  1. Using f-strings for string interpolation:
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: "My name is John and I am 25 years old."
  1. Reversing a string:
my_string = "Hello, world!"
reversed_string = my_string[::-1]
print(reversed_string)  # Output: "!dlrow ,olleH"

Note that strings in Python are immutable, which means that once a string is created, it cannot be modified. Any operation that appears to modify a string actually creates a new string object.

Leave a Comment