Strings in Python
Strings in Python
In Python, a string is a sequence of characters enclosed within single quotes (') or double quotes ("). Strings are used to represent textual data and are one of the most commonly used data types in Python.
Creating Strings
Single Quotes:
s = 'Hello, World!'Double Quotes:
s = "Hello, World!"Triple Quotes (used for multi-line strings):
Triple single quotes (
''') or triple double quotes (""") are used for creating multi-line strings.
s = '''This isa multi-linestring.'''Escape Characters:
To include special characters like quotes or newlines within a string, you can use escape sequences (preceding the character with a backslash\).s = "He said, \"Hello!\""print(s) # Output: He said, "Hello!"
String Indexing
Python strings are indexed sequences. The index starts from 0 for the first character.
s = "Hello"print(s[0]) # Output: 'H' (first character)print(s[1]) # Output: 'e' (second character)print(s[-1]) # Output: 'o' (last character)Positive indexing starts from
0to the length of the string.Negative indexing starts from
-1for the last character,-2for the second last character, and so on.
String Slicing
Slicing allows you to extract a substring from a string. The syntax is:string[start:end:step]
start: The starting index (inclusive).end: The ending index (exclusive).step: The interval (optional).
s = "Hello, World!"# Extracting substringprint(s[0:5]) # Output: 'Hello'print(s[7:]) # Output: 'World!'print(s[:5]) # Output: 'Hello'print(s[::2]) # Output: 'Hoo ol!'Negative Indices:
s = "Hello, World!"print(s[-6:-1]) # Output: 'World'
String Concatenation
You can combine multiple strings using the + operator.
s1 = "Hello"s2 = "World"s3 = s1 + " " + s2print(s3) # Output: 'Hello World'String Repetition
You can repeat a string using the * operator.
s = "Hello"print(s * 3) # Output: 'HelloHelloHello'String Length
To get the length of a string, you can use the built-in len() function.
s = "Hello, World!"print(len(s)) # Output: 13String Immutability
Strings in Python are immutable, meaning that once a string is created, you cannot change its individual characters.
s = "Hello"# The following will raise an error# s[0] = "h" # TypeError: 'str' object does not support item assignmentHowever, you can create a new string based on modifications to an existing string.
s = "Hello"s = "h" + s[1:]print(s) # Output: 'hello'String Methods
Python provides a variety of string methods that can be used to manipulate or query strings. Here are some of the most commonly used string methods:
1. String Case Methods
lower(): Converts the string to lowercase.s = "HELLO"print(s.lower()) # Output: 'hello'upper(): Converts the string to uppercase.s = "hello"print(s.upper()) # Output: 'HELLO'capitalize(): Capitalizes the first character of the string.s = "hello"print(s.capitalize()) # Output: 'Hello'
2. Searching Methods
find(sub): Returns the index of the first occurrence ofsubin the string. Returns-1if not found.s = "Hello, World!"print(s.find("World")) # Output: 7count(sub): Returns the number of occurrences ofsubin the string.s = "Hello, World!"print(s.count("o")) # Output: 2
3. String Trimming
strip(): Removes leading and trailing whitespaces from the string.s = " Hello, World! "print(s.strip()) # Output: 'Hello, World!'lstrip(): Removes leading whitespace.s = " Hello"print(s.lstrip()) # Output: 'Hello'rstrip(): Removes trailing whitespace.s = "Hello "print(s.rstrip()) # Output: 'Hello'
4. String Replacement
replace(old, new): Replaces all occurrences ofoldwithnewin the string.s = "Hello, World!"print(s.replace("World", "Python")) # Output: 'Hello, Python!'
5. String Splitting and Joining
split(sep): Splits the string into a list of substrings based on the separatorsep.s = "Hello, World!"print(s.split(", ")) # Output: ['Hello', 'World!']join(iterable): Joins elements of an iterable (e.g., a list) into a string, separated by the string itself.words = ["Hello", "World"]print(" ".join(words)) # Output: 'Hello World'
Conclusion
Strings are a fundamental part of Python, and understanding how to manipulate and work with them is essential. With Python’s built-in methods, you can easily perform a variety of operations on strings, such as searching, trimming, replacing, and formatting. These methods give you the flexibility to work with strings efficiently.