Strings_methods_fully
Strings_methods_fully
lower()
Description: Converts all characters in a string to lowercase.
Syntax:
string.lower()
Examples:
# Example 1
"HELLO".lower() # Output: "hello"
# Example 2
"Python".lower() # Output: "python"
str.upper()
Description: Converts all characters in a string to uppercase.
Syntax:
string.upper()
Examples:
# Example 1
"hello".upper() # Output: "HELLO"
# Example 2
"Python".upper() # Output: "PYTHON"
str.strip()
Description: Removes leading and trailing whitespace (or specified characters)
from the string.
Syntax:
string.strip([chars])
chars is optional, and if specified, it removes those characters from both
ends.
Examples:
# Example 1
" hello ".strip() # Output: "hello"
# Example 2
"$$$money$$$".strip('$') # Output: "money"
str.split()
Description: Splits the string into a list using a specified delimiter. The default
delimiter is any whitespace.
Syntax:
string.split([separator[, maxsplit]])
separator: Optional. The delimiter to split the string on. By default, it's
whitespace.
maxsplit: Optional. The maximum number of splits to perform.
Examples:
# Example 1
"a,b,c".split(',') # Output: ['a', 'b', 'c']
# Example 2
"hello world".split() # Output: ['hello', 'world']
# Example 3 (with maxsplit)
"apple,banana,grapes".split(',', 1) # Output: ['apple', 'banana,grapes']
str.join()
Description: Joins elements of an iterable (e.g., a list or tuple) into a single
string, with the string calling the method as the separator.
Syntax:
separator_string.join(iterable)
Examples:
# Example 1
",".join(['a', 'b', 'c']) # Output: "a,b,c"
# Example 2
" ".join(['hello', 'world']) # Output: "hello world"
# Example 3
"-".join(["2024", "12", "11"]) # Output: "2024-12-11"
str.replace()
Description: Replaces occurrences of a substring with another substring.
Syntax:
string.replace(old, new[, count])
old: The substring to be replaced.
new: The substring to replace old with.
count: Optional. The number of occurrences to replace.
Examples:
# Example 1
"hello world".replace("world", "Python") # Output: "hello Python"
# Example 2 (replacing multiple occurrences)
"apple apple apple".replace("apple", "orange") # Output: "orange orange
orange"
# Example 3 (limiting replacements)
"apple apple apple".replace("apple", "orange", 2) # Output: "orange orange
apple"
str.find()
Description: Returns the index of the first occurrence of a substring, or -1 if the
substring is not found.
Syntax:
string.find(sub[, start[, end]])
sub: The substring to search for.
start: Optional. The starting index from where the search begins.
end: Optional. The ending index for the search.
Examples:
# Example 1
"hello".find('e') # Output: 1
# Example 2
"hello".find('z') # Output: -1 (substring not found)
# Example 3 (with start and end indices)
"hello".find('l', 2, 4) # Output: 2 (finds 'l' between indices 2 and 4)
str.startswith()
Description: Checks if a string starts with the specified prefix.
Syntax:
string.startswith(prefix[, start[, end]])
prefix: The prefix to check.
start: Optional. The starting index for checking.
end: Optional. The ending index for checking.
Examples:
# Example 1
"hello".startswith('he') # Output: True
# Example 2
"hello".startswith('ell') # Output: False
# Example 3 (with start and end indices)
"hello".startswith('ll', 2, 4) # Output: True
str.endswith()
Description: Checks if a string ends with the specified suffix.
Syntax:
string.endswith(suffix[, start[, end]])
suffix: The suffix to check.
start: Optional. The starting index for checking.
end: Optional. The ending index for checking.
Examples:
# Example 1
"hello".endswith('lo') # Output: True
# Example 2
"hello".endswith('he') # Output: False
# Example 3 (with start and end indices)
"hello".endswith('lo', 0, 4) # Output: False
str.format()
Description: Performs string formatting, allowing you to insert values into a
string template.
Syntax:
"string {} template {}".format(value1, value2)
{}: Placeholder for values to be inserted.
value1, value2: The values to be inserted into the placeholders.
Examples:
# Example 1
"Hello, {}".format("world") # Output: "Hello, world"
# Example 2 (multiple placeholders)
"Hello, {}. You are {} years old.".format("John", 30) # Output: "Hello,
John. You are 30 years old."
# Example 3 (reusing the same argument)
"{} + {} = {}".format(2, 3, 2 + 3) # Output: "2 + 3 = 5"
str.title()
Description: Capitalizes the first letter of each word in the string.
Syntax:
string.title()
Examples:
# Example 1
"hello world".title() # Output: "Hello World"
# Example 2
"python programming".title() # Output: "Python Programming"
# Example 3
"hello world of python".title() # Output: "Hello World Of Python"
str.capitalize()
Description: Capitalizes the first letter of the string, and converts all other letters
to lowercase.
Syntax:
string.capitalize()
Examples:
# Example 1
"hello".capitalize() # Output: "Hello"
# Example 2
"python".capitalize() # Output: "Python"
# Example 3
"hello WORLD".capitalize() # Output: "Hello world"
str.count()
Description: Counts the occurrences of a substring within the string.
Syntax:
string.count(sub[, start[, end]])
sub: The substring to count.
start: Optional. The starting index.
end: Optional. The ending index.
Examples:
# Example 1
"banana".count('a') # Output: 3
# Example 2
"hello world".count('l') # Output: 3
# Example 3 (with start and end indices)
"hello world".count('o', 0, 5) # Output: 1 (only 'o' before the 5th character)
str.isdigit()
Description: Checks if the string contains only digits.
Syntax:
string.isdigit()
Examples:
# Example 1
"123".isdigit() # Output: True
# Example 2
"123abc".isdigit() # Output: False
# Example 3
"4567".isdigit() # Output: True
str.isalpha()
Description: Checks if the string contains only alphabetic characters.
Syntax:
string.isalpha()
Examples:
# Example 1
"hello".isalpha() # Output: True
# Example 2
"hello123".isalpha() # Output: False
# Example 3
"world".isalpha() # Output: True
str.isalnum()
Description: Checks if the string contains only alphanumeric characters (letters
and numbers).
Syntax:
string.isalnum()
Examples:
# Example 1
"hello123".isalnum() # Output: True
# Example 2
"hello@123".isalnum() # Output: False
# Example 3
"12345".isalnum() # Output: True
str.lstrip()
Description: Removes leading (left) whitespace or specified characters.
Syntax:
string.lstrip([chars])
Examples:
# Example 1
" hello".lstrip() # Output: "hello"
# Example 2
"$$$money".lstrip('$') # Output: "money"
# Example 3
" hello".lstrip() # Output: "hello"
str.rstrip()
Description: Removes trailing (right) whitespace or specified characters.
Syntax:
string.rstrip([chars])
Examples:
# Example 1
"hello ".rstrip() # Output: "hello"
# Example 2
"money$$$".rstrip('$') # Output: "money"
# Example 3
"hello ".rstrip() # Output: "hello"
str.zfill()
Description: Pads the string with zeros on the left to fill a specified width.
Syntax:
string.zfill(width)
width: The total width of the string (including the original string length).
Examples:
# Example 1
"42".zfill(5) # Output: "00042"
# Example 2
"7".zfill(4) # Output: "0007"
# Example 3
"12345".zfill(7) # Output: "0012345"
str.partition()
Description: Splits the string into three parts: before the delimiter, the delimiter
itself, and after the delimiter.
Syntax:
string.partition(sep)
sep: The delimiter to split on.
Examples:
# Example 1
"hello world".partition(' ') # Output: ('hello', ' ', 'world')
# Example 2
"apple,orange,banana".partition(',') # Output: ('apple', ',', 'orange,banana')
# Example 3 (without delimiter found)
"hello".partition('x') # Output: ('hello', '', '')
str.swapcase()
Description: Swaps uppercase characters to lowercase and vice versa.
Syntax:
string.swapcase()
Examples:
# Example 1
"Hello".swapcase() # Output: "hELLO"
# Example 2
"PyThOn".swapcase() # Output: "pYtHoN"
# Example 3
"cOdIng".swapcase() # Output: "CoDiNG"
str.casefold()
Description: Converts the string to lowercase in a more aggressive way than
lower(), making it suitable for case-insensitive comparisons.
Syntax:
string.casefold()
Examples:
# Example 1
"HELLO".casefold() # Output: "hello"
# Example 2
"Python".casefold() # Output: "python"
# Example 3 (useful for case-insensitive comparisons)
"HELLO".casefold() == "hello".casefold() # Output: True
str.index()
Description: Returns the index of the first occurrence of a substring. Raises a
ValueError if the substring is not found.
Syntax:
string.index(sub[, start[, end]])
sub: The substring to search for.
start: Optional. The starting index.
end: Optional. The ending index.
Examples:
# Example 1
"hello".index('e') # Output: 1
# Example 2
"banana".index('a') # Output: 1
# Example 3 (raises ValueError if not found)
"hello".index('z') # Raises ValueError
str.rfind()
Description: Finds the last occurrence of a substring or returns -1 if not found.
Syntax:
string.rfind(sub[, start[, end]])
sub: The substring to search for.
start: Optional. The starting index.
end: Optional. The ending index.
Examples:
# Example 1
"banana".rfind('a') # Output: 5 (last occurrence of 'a')
# Example 2
"hello world".rfind('o') # Output: 7 (last occurrence of 'o')
# Example 3 (returns -1 if not found)
"apple".rfind('z') # Output: -1
str.rsplit()
Description: Splits the string from the right into a list. You can specify the
delimiter and the maximum number of splits.
Syntax:
string.rsplit([separator[, maxsplit]])
separator: Optional. The delimiter to split on (default is any whitespace).
maxsplit: Optional. The maximum number of splits to perform.
Examples:
# Example 1
"a,b,c".rsplit(',', 1) # Output: ['a,b', 'c']
# Example 2
"hello world example".rsplit(' ', 1) # Output: ['hello world', 'example']
# Example 3 (without maxsplit)
"apple orange banana".rsplit() # Output: ['apple', 'orange', 'banana']
str.center()
Description: Centers the string within a specified width, padding with a specified
character (default is space).
Syntax:
string.center(width[, fillchar])
width: The total width of the resulting string.
fillchar: Optional. The character to use for padding (default is space).
Examples:
# Example 1
"hello".center(10, '-') # Output: "--hello---"
# Example 2
"hello".center(12, '*') # Output: "***hello***"
# Example 3
"Python".center(20, '#') # Output: "####Python######"
str.ljust()
Description: Left-aligns the string within a field of specified width, padding with
a specified character (default is space).
Syntax:
string.ljust(width[, fillchar])
width: The total width of the resulting string.
fillchar: Optional. The character to use for padding (default is space).
Examples:
# Example 1
"hello".ljust(10, '-') # Output: "hello-----"
# Example 2
"python".ljust(12, '*') # Output: "python******"
# Example 3
"apple".ljust(8, '0') # Output: "apple000"
str.rjust()
Description: Right-aligns the string within a field of specified width, padding
with a specified character (default is space).
Syntax:
string.rjust(width[, fillchar])
width: The total width of the resulting string.
fillchar: Optional. The character to use for padding (default is space).
Examples:
# Example 1
"hello".rjust(10, '-') # Output: "-----hello"
# Example 2
"python".rjust(12, '#') # Output: "####python"
# Example 3
"apple".rjust(8, '0') # Output: "000apple"
str.splitlines()
Description: Splits the string at line breaks and returns a list of lines.
Syntax:
string.splitlines([keepends])
keepends: Optional. If True, the newline characters are included in the
output.
Examples:
# Example 1
"line1\nline2".splitlines() # Output: ['line1', 'line2']
# Example 2 (with keepends=True)
"line1\nline2".splitlines(True) # Output: ['line1\n', 'line2']
# Example 3
"hello\nworld\npython".splitlines() # Output: ['hello', 'world', 'python']
str.expandtabs()
Description: Expands tabs into spaces. The number of spaces can be specified.
Syntax:
string.expandtabs([tabsize])
tabsize: Optional. The number of spaces to replace each tab. Default is 8.
Examples:
# Example 1
"hello\tworld".expandtabs(4) # Output: "hello world"
# Example 2 (default tabsize)
"hello\tworld".expandtabs() # Output: "hello world"
# Example 3 (with tabsize=2)
"hello\tworld".expandtabs(2) # Output: "hello world"
str.islower()
Description: Checks if all characters in the string are lowercase.
Syntax:
string.islower()
Examples:
# Example 1
"hello".islower() # Output: True
# Example 2
"Hello".islower() # Output: False (because 'H' is uppercase)
# Example 3
"python".islower() # Output: True
str.isupper()
Description: Checks if all characters in the string are uppercase.
Syntax:
string.isupper()
Examples:
# Example 1
"HELLO".isupper() # Output: True
# Example 2
"Hello".isupper() # Output: False (because 'H' is uppercase but 'ello' is not)
# Example 3
"PYTHON".isupper() # Output: True
str.isspace()
Description: Checks if the string contains only whitespace characters.
Syntax:
string.isspace()
Examples:
# Example 1
" ".isspace() # Output: True
# Example 2
"\t\n ".isspace() # Output: True (tabs and newlines are whitespace
characters)
# Example 3
"hello".isspace() # Output: False (because it's not just whitespace)
str.isprintable()
Description: Checks if all characters in the string are printable characters
(characters that can be displayed).
Syntax:
string.isprintable()
Examples:
# Example 1
"hello".isprintable() # Output: True
# Example 2
"hello\nworld".isprintable() # Output: False (because '\n' is not printable)
# Example 3
"hello\tworld".isprintable() # Output: False (because '\t' is not printable)
str.isidentifier()
Description: Checks if the string is a valid Python identifier (i.e., it follows
Python naming rules).
Syntax:
string.isidentifier()
Examples:
# Example 1
"variable_name".isidentifier() # Output: True
# Example 2
"2variable".isidentifier() # Output: False (because it starts with a digit)
# Example 3
"hello".isidentifier() # Output: True
str.maketrans()
Description: Creates a translation table for str.translate().
Syntax:
str.maketrans(x, y)
x: The characters to replace.
y: The characters to replace with.
Examples:
# Example 1
str.maketrans('abc', '123') # Output: translation table that maps 'a' to '1', 'b' to
'2', 'c' to '3'
# Example 2
str.maketrans('aeiou', '12345') # Output: translation table that maps vowels
to numbers
str.translate()
Description: Translates the string using a translation table created with
str.maketrans().
Syntax:
string.translate(table)
table: The translation table created by str.maketrans().
Examples:
# Example 1
"abc".translate(str.maketrans('abc', '123')) # Output: "123"
# Example 2
"hello".translate(str.maketrans('aeiou', '12345')) # Output: "h2ll4"
str.encode()
Description: Encodes the string into bytes using a specified encoding (default is
UTF-8).
Syntax:
string.encode(encoding='utf-8', errors='strict')
encoding: The encoding format (default is 'utf-8').
errors: The error handling scheme (default is 'strict').
Examples:
# Example 1
"hello".encode('utf-8') # Output: b'hello'
# Example 2
"hello".encode('ascii') # Output: b'hello'
# Example 3 (with error handling)
"hello".encode('ascii', errors='ignore') # Output: b'hello'