Strings
A string is a sequence of characters. In Python, strings are immutable, meaning they cannot be changed after they’re created. You can define a string using single, double, or triple quotes.
Raw Strings
Section titled “Raw Strings”Raw strings are useful for handling special characters like backslashes (\). By prefixing a string with r or R, you tell Python to treat backslashes as literal characters instead of escape characters.
# without raw stringprint('C:\\nowhere') # Output: C:\nowhere
# with raw stringprint(r'C:\\nowhere') # Output: C:\\nowhereAccessing Strings
Section titled “Accessing Strings”Strings in Python are arrays of bytes representing Unicode characters. While Python doesn’t have a char data type, a single character is simply a string with a length of 1. You can access individual characters or parts of a string using square brackets [].
1. Strings as Arrays: You can access specific characters by their index.
a = "Hello, World!"print(a[1]) # Output: e2. Looping Through a String:
Because strings are sequences, you can easily iterate through each character using a for loop.
for x in "banana": print(x)3. String Length:
Use the len() function to get the number of characters in a string.
a = "Hello, World!"print(len(a)) # Output: 134. Checking for Presence:
The in keyword checks if a substring is present. The not in keyword checks for its absence.
txt = "The best things in life are free!"print("free" in txt) # Output: True
if "expensive" not in txt: print("No, 'expensive' is NOT present.")String Slicing
Section titled “String Slicing”Slicing lets you extract a substring by specifying a range of indices. The syntax is string[start:end], where the end index is exclusive.
1. Basic Slicing:
b = "Hello, World!"print(b[2:5]) # Output: llo2. Slice from the Start:
Omitting the start index begins the slice from the first character.
b = "Hello, World!"print(b[:5]) # Output: Hello3. Slice to the End:
Omitting the end index extends the slice to the last character.
b = "Hello, World!"print(b[2:]) # Output: llo, World!4. Negative Indexing: Negative indices slice from the end of the string.
b = "Hello, World!"print(b[-5:-2]) # Output: orl5. Slicing with Skip Value:
You can add a third parameter, step, to skip characters. string[start:end:step]
word = "amazing"print(word[1:6:2]) # Output: mznUpdating a String
Section titled “Updating a String”Since strings are immutable, you can’t modify them directly. Instead, you create a new string by combining parts of the original string. This creates a new memory location for the new string.
my_string = "Python"new_string = my_string[:2] + "thon"print(new_string) # Output: PythonConcatenation and Repetition
Section titled “Concatenation and Repetition”You can combine strings using the + operator (concatenation) and repeat them using the * operator.
a = "Hello"b = "World"c = a + " " + bprint(c) # Output: Hello World
repeat_string = "Python" * 3print(repeat_string) # Output: PythonPythonPythonEscape Characters
Section titled “Escape Characters”Escape characters let you include special characters in a string. They are preceded by a backslash (\).
| Code | Result |
|---|---|
\' | Single Quote |
\\ | Backslash |
\n | New Line |
\t | Tab |
String Operators
Section titled “String Operators”| Operator | Description | Example |
|---|---|---|
+ | Concatenation | 'Hello' + 'Python' gives 'HelloPython' |
* | Repetition | 'Hello' * 2 gives 'HelloHello' |
[] | Slice | 'Hello'[1] gives 'e' |
[:] | Range Slice | 'Hello'[1:4] gives 'ell' |
in | Membership | 'H' in 'Hello' gives True |
not in | Membership | 'M' not in 'Hello' gives True |
r/R | Raw String | r'\n' prints \n |
String Formatting
Section titled “String Formatting”You can’t directly combine strings and numbers with the + operator. Python provides several ways to format strings.
1. % Format Operator (Legacy):
This operator is similar to printf() in C.
print("My name is %s and weight is %d kg!" % ('Zara', 21))# Output: My name is Zara and weight is 21 kg!2. F-Strings (Python 3.6+):
F-Strings are the modern, preferred way to format strings. They’re more readable and efficient. Prefix the string with f and use curly braces {} as placeholders for variables or expressions.
age = 36txt = f"My name is John, I am {age}"print(txt) # Output: My name is John, I am 36You can also apply modifiers inside the placeholders.
price = 59txt = f"The price is {price:.2f} dollars"print(txt) # Output: The price is 59.00 dollarsString Methods
Section titled “String Methods”Python’s string methods are powerful tools for manipulating and inspecting strings.
-
capitalize(): Converts the first character to uppercase.s = "python fundamentals: a complete guide for beginners"print(f"capitalize(): '{s.capitalize()}'")# Output:# capitalize(): 'Python fundamentals: a complete guide for beginners' -
upper(): Converts all characters to uppercase.s = "python fundamentals: a complete guide for beginners"print(f"upper(): '{s.upper()}'")# Output:# upper(): 'PYTHON FUNDAMENTALS: A COMPLETE GUIDE FOR BEGINNERS' -
lower(): Converts all characters to lowercase.s = "PYTHON FUNDAMENTALS: A COMPLETE GUIDE FOR BEGINNERS"print(f"lower(): '{s.lower()}'")# Output:# lower(): 'python fundamentals: a complete guide for beginners' -
strip(): Removes leading and trailing whitespace.s = " python fundamentals: a complete guide for beginners "print(f"strip(): '{s.strip()}'")# Output:# strip(): 'python fundamentals: a complete guide for beginners' -
split(separator): Splits a string into a list of substrings.s = "python,fundamentals,a,complete,guide,for,beginners"print(f"split(','): {s.split(',')}")# Output:# split(','): ['python', 'fundamentals', 'a', 'complete', 'guide', 'for', 'beginners'] -
join(iterable): Joins elements of an iterable into a single string.s = ['python', 'fundamentals', 'a', 'complete', 'guide', 'for', 'beginners']print(f"join(): ' '.join(s)")# Output:# join(): 'python fundamentals a complete guide for beginners' -
replace(old, new): Replaces a substring with a new one.s = "a guide for python beginners"print(f"replace(): '{s.replace('python', 'Java')}'")# Output:# replace(): 'a guide for Java beginners' -
count(substring): Counts occurrences of a substring.s = "python is fun, python is easy"print(f"count('python'): {s.count('python')}")# Output:# count('python'): 2 -
find(substring): Finds the index of a substring, returns-1if not found.s = "python is fun"print(f"find('fun'): {s.find('fun')}")# Output:# find('fun'): 10 -
startswith(prefix): Checks if the string begins with a specific prefix.s = "python is fun"print(f"startswith('python'): {s.startswith('python')}")# Output:# startswith('python'): True -
endswith(suffix): Checks if the string ends with a specific suffix.s = "python is fun"print(f"endswith('fun'): {s.endswith('fun')}")# Output:# endswith('fun'): True -
isalnum(): Checks if all characters are alphanumeric.s1 = "python123"s2 = "python!"print(f"isalnum() for '{s1}': {s1.isalnum()}")print(f"isalnum() for '{s2}': {s2.isalnum()}")# Output:# isalnum() for 'python123': True# isalnum() for 'python!': False -
isalpha(): Checks if all characters are alphabetic.s1 = "python"s2 = "python123"print(f"isalpha() for '{s1}': {s1.isalpha()}")print(f"isalpha() for '{s2}': {s2.isalpha()}")# Output:# isalpha() for 'python': True# isalpha() for 'python123': False -
isdigit(): Checks if all characters are digits.s1 = "12345"s2 = "123a"print(f"isdigit() for '{s1}': {s1.isdigit()}")print(f"isdigit() for '{s2}': {s2.isdigit()}")# Output:# isdigit() for '12345': True# isdigit() for '123a': False -
isupper()/islower(): Checks the case of characters.s1 = "PYTHON"s2 = "python"print(f"isupper() for '{s1}': {s1.isupper()}")print(f"islower() for '{s2}': {s2.islower()}")# Output:# isupper() for 'PYTHON': True# islower() for 'python': True -
title(): Converts the first letter of each word to uppercase.s = "python is fun"print(f"title(): '{s.title()}'")# Output:# title(): 'Python Is Fun' -
swapcase(): Swaps the case of all characters.s = "Python is FUN"print(f"swapcase(): '{s.swapcase()}'")# Output:# swapcase(): 'pYTHON IS fun'
The above string methods are the methods which are used mostly by python programmers.
There are a whole lot of other methods that python provides which can always be referred from the python docs: Python String Methods