## Strings in Python
A string in Python is a sequence of characters. Strings are immutable, meaning once they are created, they cannot be changed.
### Creating Strings
You can create strings using single quotes, double quotes, or triple quotes (for multi-line strings).
```python
# Single quotes
str1 = 'Hello'
# Double quotes
str2 = "World"
# Triple quotes
str3 = '''This is a
multi-line
string'''
```
### Accessing Characters in a String
You can access characters in a string using indexing. Python uses zero-based indexing, so the first character has index 0.
```python
s = "Hello"
# Accessing first character
print(s[0]) # Output: H
# Accessing last character
print(s[-1]) # Output: o
```
### Slicing Strings
You can get a substring using slicing.
```python
s = "Hello, World!"
# Slicing from index 0 to 4
print(s[0:5]) # Output: Hello
# Slicing from index 7 to end
print(s[7:]) # Output: World!
# Slicing with negative indices
print(s[-6:]) # Output: World!
```
### String Methods
Python provides a variety of built-in string methods for common operations.
#### Changing Case
```python
s = "Hello, World!"
# Convert to uppercase
print(s.upper()) # Output: HELLO, WORLD!
# Convert to lowercase
print(s.lower()) # Output: hello, world!
# Capitalize the first letter
print(s.capitalize()) # Output: Hello, world!
# Title case
print(s.title()) # Output: Hello, World!
```
#### Searching and Replacing
```python
s = "Hello, World!"
# Find the index of a substring
print(s.find('World')) # Output: 7
# Replace a substring
print(s.replace('World', 'Universe')) # Output: Hello, Universe!
```
#### Splitting and Joining
```python
s = "Hello, World!"
# Split string into a list of substrings
print(s.split(', ')) # Output: ['Hello', 'World!']
# Join a list of strings into a single string
words = ['Hello', 'World!']
print(' '.join(words)) # Output: Hello World!
```
### String Formatting
Python offers several ways to format strings.
#### Using the `%` Operator
```python
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string) # Output: My name is Alice and I am 30 years old.
```
#### Using `str.format()`
```python
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # Output: My name is Alice and I am 30 years old.
```
#### Using f-Strings (Python 3.6+)
```python
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: My name is Alice and I am 30 years old.
```
### String Immutability
Strings in Python are immutable, meaning you cannot change a string after it has been created. Instead, you create new strings.
```python
s = "Hello"
# Attempt to change the first character (will raise an error)
# s[0] = 'h' # TypeError: 'str' object does not support item assignment
# Correct way to change a string
s = 'h' + s[1:]
print(s) # Output: hello
```
### Useful String Methods
Here are a few more useful string methods:
- `strip()`: Removes whitespace from the beginning and end of a string.
- `startswith()`: Checks if a string starts with a specified substring.
- `endswith()`: Checks if a string ends with a specified substring.
- `isalpha()`: Checks if all characters in the string are alphabetic.
- `isdigit()`: Checks if all characters in the string are digits.
- `islower()`: Checks if all characters in the string are lowercase.
- `isupper()`: Checks if all characters in the string are uppercase.
### Examples
Here are some practical examples of using strings in Python:
```python
# Removing whitespace
s = " Hello, World! "
print(s.strip()) # Output: Hello, World!
# Checking start and end
print(s.startswith(" He")) # Output: True
print(s.endswith("ld! ")) # Output: True
# Checking character properties
print("abc".isalpha()) # Output: True
print("123".isdigit()) # Output: True
# Checking case
print("hello".islower()) # Output: True
print("HELLO".isupper()) # Output: True
```
5 practice questions on strings in Python:
1. **Reverse a String:**
Write a function `reverse_string(s)` that takes a string `s` and returns the string reversed.
```python
def reverse_string(s):
# Your code here
pass
# Example usage
print(reverse_string("hello")) # Output: "olle"
```
2. **Count Vowels:**
Write a function `count_vowels(s)` that takes a string `s` and returns the number of vowels (a, e, i, o, u) in the string.
```python
def count_vowels(s):
# Your code here
pass
# Example usage
print(count_vowels("hello")) # Output: 2
```
3. **Check Palindrome:**
Write a function `is_palindrome(s)` that takes a string `s` and returns `True` if the string is a palindrome (reads the same forwards and backwards), and `False` otherwise.
```python
def is_palindrome(s):
# Your code here
pass
# Example usage
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
```
4. **Find the Longest Word:**
Write a function `longest_word(s)` that takes a string `s` and returns the longest word in the string. Assume that words are separated by spaces.
```python
def longest_word(s):
# Your code here
pass
# Example usage
print(longest_word("The quick brown fox jumps over the lazy dog")) # Output: "jumps"
```
5. **Character Frequency:**
Write a function `char_frequency(s)` that takes a string `s` and returns a dictionary where the keys are characters and the values are the number of times each character appears in the string.
```python
def char_frequency(s):
# Your code here
pass
# Example usage
print(char_frequency("hello")) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
```
0 Comments