October 15, 2024

Python String

Python strings are sequences of characters enclosed within single quotes ('), double quotes ("), triple single quotes ('''), or triple double quotes ("""). Strings are a fundamental data type in Python and are used to represent textual data. Python provides a rich set of operations and methods for working with strings.

1. Creating Strings

Strings in Python can be created using single, double, or triple quotes.

# Single quotes
string1 = 'Hello, World!'

# Double quotes
string2 = "Hello, World!"

# Triple single quotes (for multi-line strings)
string3 = '''Hello,
World!'''

# Triple double quotes (for multi-line strings)
string4 = """Hello,
World!"""

2. Accessing Characters in a String

Strings in Python are indexed, meaning each character in the string has a specific position (index). You can access individual characters or substrings using square brackets ([]).

  • Indexing: Accessing a single character using its index.
string = "Python"
print(string[0])  # Output: 'P'
print(string[-1]) # Output: 'n' (negative index starts from the end)
  • Slicing: Accessing a range of characters (substring).

print(string[0:3]) # Output: 'Pyt'
print(string[2:]) # Output: 'thon'
print(string[:4]) # Output: 'Pyth'
print(string[-3:]) # Output: 'hon'

3. String Immutability

Strings in Python are immutable, meaning once a string is created, its contents cannot be changed. Any operation that modifies a string will create a new string instead of modifying the original one.
string = "Python"
# string[0] = 'J' # This will raise an error
# To change a string, you must create a new one
new_string = 'J' + string[1:]
print(new_string) # Output: 'Jython'

4. String Concatenation and Repetition

  • Concatenation: You can concatenate (join) strings using the + operator.

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: 'Hello World'

Repetition: You can repeat strings using the * operator.
str3 = "Hi! "
print(str3 * 3) # Output: 'Hi! Hi! Hi! '

5. String Methods

Python provides a variety of built-in methods for string manipulation. Here are some commonly used string methods:

  • str.lower(): Converts all characters in the string to lowercase.

string = "Hello World"
print(string.lower()) # Output: 'hello world'

str.upper(): Converts all characters in the string to uppercase.

print(string.upper()) # Output: 'HELLO WORLD'

str.title(): Converts the first character of each word to uppercase.

print(string.title()) # Output: 'Hello World'


str.strip(): Removes leading and trailing whitespace (or specified characters).

string = " Hello World "
print(string.strip()) # Output: 'Hello World'

str.replace(old, new): Replaces occurrences of a substring with another substring.
string = "Hello World"
print(string.replace("World", "Python")) # Output: 'Hello Python'

str.split(separator): Splits the string into a list of substrings based on a separator.
string = "apple,banana,cherry"
print(string.split(',')) # Output: ['apple', 'banana', 'cherry']

str.join(iterable): Joins elements of an iterable (like a list) into a single string, with a specified separator.

list_of_fruits = ['apple', 'banana', 'cherry']
print(", ".join(list_of_fruits)) # Output: 'apple, banana, cherry'

str.find(substring): Returns the lowest index in the string where the substring is found. Returns -1 if not found.

string = "Hello World"
print(string.find("World")) # Output: 6

str.startswith(prefix): Returns True if the string starts with the specified prefix.

print(string.startswith("Hello")) # Output: True

str.endswith(suffix): Returns True if the string ends with the specified suffix.

print(string.endswith("World")) # Output: True

6. String Formatting

Python provides several ways to format strings:

a. Using the % Operator (Old Style)

name = "Alice"
age = 25
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 25 years old.'

b. Using str.format() (New Style)
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # Output: 'My name is Alice and I am 25 years old.'

c. Using f-Strings (Python 3.6+)

formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: 'My name is Alice and I am 25 years old.'

7. Multi-line Strings

Multi-line strings are created using triple quotes. They allow you to write strings that span multiple lines.

multi_line_string = """This is a
multi-line
string."""
print(multi_line_string)

Output:

This is a
multi-line
string.

8. Escape Sequences

Escape sequences allow you to include special characters in strings, such as newlines (\n), tabs (\t), and quotes (\', \").
escaped_string = "He said, \"Hello, World!\"\nNew line starts here."
print(escaped_string)

Output:
He said, "Hello, World!"
New line starts here.

9. Raw Strings

Raw strings are created by prefixing the string with an r or R. In raw strings, escape sequences are not processed, which is useful when dealing with regular expressions or file paths.

raw_string = r"C:\Users\Name\Desktop"
print(raw_string) # Output: 'C:\Users\Name\Desktop'

10. String Length

You can find the length of a string using the len() function.
string = "Hello"
print(len(string)) # Output: 5

11. String Membership

You can check if a substring exists within a string using the in and not in operators.
string = "Hello, World"
print("Hello" in string) # Output: True
print("Python" not in string) # Output: True

12. Iterating Over a String

You can iterate over each character in a string using a for loop.
for char in "Python":
print(char)

Output:

P
y
t
h
o
n

13. Common String Operations

  • Reversing a String:

string = "Python"
reversed_string = string[::-1]
print(reversed_string) # Output: 'nohtyP'

Checking if a String is a Palindrome:

def is_palindrome(s):
return s == s[::-1]

print(is_palindrome("radar")) # Output: True
print(is_palindrome("python")) # Output: False

14. String Methods Summary

Here’s a quick reference table for common string methods:

Method Description
str.lower() Converts all characters to lowercase.
str.upper() Converts all characters to uppercase.
str.title() Converts the first character of each word to uppercase.
str.strip() Removes leading and trailing whitespace.
str.replace(old, new) Replaces all occurrences of a substring with another.
str.split(separator) Splits the string into a list of substrings.
str.join(iterable) Joins elements of an iterable into a single string.
str.find(substring) Returns the index of the first occurrence of a substring.
str.startswith(prefix) Checks if the string starts with a specified prefix.
str.endswith(suffix) Checks if the string ends with a specified suffix.
str.isdigit() Checks if all characters in the string are digits.
str.isalpha() Checks if all characters in the string are alphabetic.
str.isalnum() Checks if all characters in the string are alphanumeric.
str.isspace() Checks if the string consists only of whitespace.

15. String Encoding and Decoding

  • Encoding: Convert a string to bytes using a specific encoding (like UTF-8).

string = "Hello"
encoded_string = string.encode("utf-8")
print(encoded_string) # Output: b'Hello'

Decoding: Convert bytes back to a string using a specific encoding.
decoded_string = encoded_string.decode("utf-8")
print(decoded_string) # Output: 'Hello'

16. Unicode and Strings

Python strings support Unicode, which means they can handle characters from any language.
unicode_string = "你好" # 'Hello' in Chinese
print(unicode_string) # Output: 你好

Conclusion

Strings are a fundamental and versatile data type in Python, used for representing and manipulating text. Python provides a rich set of tools and methods for working with strings, making it easy to perform operations like concatenation, slicing, formatting, and more. Understanding how to work with strings is essential for effective Python programming.