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:
- Declaring a string variable:
my_string = "Hello, world!"
print(my_string) # Output: "Hello, world!"
- Accessing characters in a string using indexing:
my_string = "Hello, world!"
print(my_string[0]) # Output: "H"
print(my_string[7]) # Output: "w"
- Slicing a string to extract a substring:
my_string = "Hello, world!"
print(my_string[0:5]) # Output: "Hello"
- Concatenating strings:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: "John Doe"
- 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."
- 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."
- 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.