In Python, a string is a collection of characters enclosed in single quotes (`'`), double quotes (`"`), or triple quotes (`'''` or `"""`). Single quotes and double quotes are often used interchangeably, as there is no difference in the way Python treats them. Triple quotes are typically used for multi-line strings. For example:
single_quotes = 'Hello, World!'
double_quotes = "Hello, World!"
multi_line = '''Hello,
World!'''
In all the above instances, the output would be `Hello, World!` The last one is specifically useful when you want to include several lines in your string.
Indexing Strings:
Python strings are arrays of bytes representing Unicode characters. Python does not have a character data type; a single character is simply a string with a length of 1.
Each character in a string has a position or an index, which Python can refer to directly. Python supports zero-based indexing, which means the first character in a string has index 0, the next has index 1, and so on. Additionally, Python also supports negative indexing, where -1 refers to the last character, -2 refers to the second-last character, and so on.
You can use square brackets `[]` to access elements of the string by referring to their index number.
Let's look at an example:
text = "PYTHON"
print(text[0]) # Output: P
print(text[-1]) # Output : N
Slicing Strings:
Slicing in Python is a feature that enables accessing parts of sequences like strings. You can slice a string using the syntax `[start:stop:step]`. Here, `start` denotes the index where the slice starts, `stop` denotes where it ends, and `step` denotes the increment between each index for slicing.
greet = "Hello, Python!"
print(greet[0:5]) # Output: Hello
print(greet[7:13]) # Output : Python
print(greet[0:5 : 2]) # Output : Hlo
print(greet[:: - 1]) # Output : !nohtyP, olleH(Reversing the string)
String Length:
The built-in `len()` function returns the length (number of characters) of a string:
greet = "Hello, Python!"
print(len(greet)) # Output: 14
Checking String:
We can check if a certain phrase or character is present in a string. We can use the keyword `in` or `not in` to check if the string is present or not respectively.
txt = "Python programming is easy."
print("easy" in txt) # Output: True
print("hard" not in txt) # Output : True
Modifying Strings:
Strings in Python are immutable. This means you cannot change an existing string. But you can generate a new string based on the old one.
However, Python provides many methods that can perform transformations on the strings. Here are a few examples:
Convert to Upper Case:
The `upper()` function converts all the characters in a string to uppercase letters.
my_string = "Hello, World!"
print(my_string.upper()) # Output: HELLO, WORLD!
Convert to Lower Case:
The `lower()` function converts all the characters in a string to lowercase letters.
my_string = "Hello, World!"
print(my_string.lower()) # Output: hello, world!
Remove Whitespace:
The `strip()` function removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)
my_string = " Hello, World! "
print(my_string.strip()) # Output: "Hello, World!"
Replace String:
The `replace()` function replaces a string with another string.
text = "I like Java"
print(text.replace("Java", "Python")) # Output: "I like Python"
Split String:
The `split()` function splits the string into substrings if it finds instances of the separator.
my_string = "Hello, World!"
print(my_string.split(",")) # Output: ['Hello', ' World!']
String Concatenation:
In Python, you can use the `+` operator to combine multiple strings together; this is known as string concatenation.
str1 = "Python"
str2 = "Programming"
str3 = str1 + " " + str2
print(str3) # Output: Python Programming
String Formatting:
When working with Python, there is often a need to integrate different data types into a single string for display or other purposes. However, Python doesn't allow direct concatenation of strings with other data types, such as integers or floats.
For instance, trying to concatenate an integer to a string like this will throw a TypeError:
age = 25
message = "Happy " + age + "th birthday!"
print(message) # This will result in a TypeError
Luckily, Python offers an easy workaround through the `format()` method associated with strings. This method enables you to insert any data type into a string by placing placeholders, represented by curly braces `{}`, in the string.
age = 25
message = "Happy {}th birthday!"
print(message.format(age)) # Output: Happy 25th birthday!
In this case, `age` is passed as an argument to the `format()` method, and it substitutes the `{}` placeholder in the `message` string.
One of the powerful features of the `format()` method is its ability to take multiple arguments. The arguments are then inserted into the placeholders in the same order they appear in the method call.
quantity = 5
item = "balloons"
price = 1.25
purchase = "I bought {} {} for {} dollars each."
print(purchase.format(quantity, item, price))
# Output: I bought 5 balloons for 1.25 dollars each.
In the example above, the placeholders are filled with the `quantity`, `item`, and `price` in that exact order.