0% found this document useful (0 votes)
7 views6 pages

Python Methods Reference

This document serves as a comprehensive reference for Python methods related to strings, integers, and floats. It includes detailed descriptions of various methods, their syntax, and examples of usage, covering case conversion, searching, validation, modification, formatting, and arithmetic operations. Additionally, it offers quick tips for competitive programming, highlighting commonly used operations for efficient coding.

Uploaded by

aicanbegreater
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

Python Methods Reference

This document serves as a comprehensive reference for Python methods related to strings, integers, and floats. It includes detailed descriptions of various methods, their syntax, and examples of usage, covering case conversion, searching, validation, modification, formatting, and arithmetic operations. Additionally, it offers quick tips for competitive programming, highlighting commonly used operations for efficient coding.

Uploaded by

aicanbegreater
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🐍

Python Methods Reference


String • Integer • Float

🔤 STRING METHODS

💡 Strings are immutable — all methods return a NEW string, they don't change the original. import math is not
needed for strings.

▸ Case Conversion
Method / Syntax What It Does Example
.upper() Converts all letters to UPPERCASE "hello".upper() → "HELLO"

.lower() Converts all letters to lowercase "HELLO".lower() → "hello"

.capitalize() First letter upper, rest lower "hELLO".capitalize() → "Hello"

"hello world".title() → "Hello


.title() First letter of every word upper World"

.swapcase() Swaps upper↔lower for every letter "Hello".swapcase() → "hELLO"

.casefold() Aggressive lowercase (for "ß".casefold() → "ss"


comparisons)

▸ Searching & Finding


Method / Syntax What It Does Example

.find(sub) Returns index of first match, -1 if not "hello".find("l") → 2


found

.rfind(sub) Returns index of last match, -1 if not "hello".rfind("l") → 3


found

.index(sub) Like find() but raises error if not found "hello".index("e") → 1

.rindex(sub) Like rfind() but raises error if not found "hello".rindex("l") → 3

.count(sub) Counts non-overlapping occurrences "banana".count("a") → 3

"hello".startswith("he") →
.startswith(pre) True if string starts with prefix True

.endswith(suf) True if string ends with suffix "hello".endswith("lo") → True

.in keyword True if substring is inside string "ell" in "hello" → True


▸ Checking / Validation
Method / Syntax What It Does Example
.isalpha() True if all chars are letters "abc".isalpha() → True

.isdigit() True if all chars are digits "123".isdigit() → True

.isalnum() True if all chars are letters or digits "abc123".isalnum() → True

.isspace() True if all chars are whitespace " ".isspace() → True

.isupper() True if all cased letters are uppercase "HELLO".isupper() → True

.islower() True if all cased letters are lowercase "hello".islower() → True

.istitle() True if string is in title case "Hello World".istitle() → True

.isnumeric() True if all chars are numeric (incl. ², ½) "²".isnumeric() → True

.isdecimal() True if all chars are 0-9 decimal digits "123".isdecimal() → True

.isidentifier() True if valid Python variable name "my_var".isidentifier() → True

.isprintable() True if all chars are printable "hello".isprintable() → True

▸ Modifying / Cleaning
Method / Syntax What It Does Example
.strip() Removes whitespace from both ends " hi ".strip() → "hi"

.lstrip() Removes whitespace from left only " hi ".lstrip() → "hi "

.rstrip() Removes whitespace from right only " hi ".rstrip() → " hi"

.strip(chars) Removes specified chars from both "xxhelloxx".strip("x") →


ends "hello"

.replace(old, new) Replaces all occurrences of old with "aabbcc".replace("b","x") →


new "aaxxcc"

.replace(old,new,n "aaa".replace("a","b",2) →
Replaces only first n occurrences
) "bba"

.removeprefix(pre) Removes prefix if present (Python "unhappy".removeprefix("un") →


3.9+) "happy"

.removesuffix(suf) Removes suffix if present (Python "[Link]".removesuffix(".py")


3.9+) → "hello"

▸ Splitting & Joining


Method / Syntax What It Does Example
"a b c".split() →
.split() Splits on whitespace into a list ["a","b","c"]

"a,b,c".split(",") →
.split(sep) Splits on a specific separator ["a","b","c"]

"a,b,c".split(",",1) →
.split(sep, n) Splits at most n times ["a","b,c"]

"a,b,c".rsplit(",",1) →
.rsplit(sep, n) Splits from right, at most n times ["a,b","c"]
"a\nb\nc".splitlines() →
.splitlines() Splits on line boundaries ["a","b","c"]

[Link](list) Joins list elements with separator ",".join(["a","b"]) → "a,b"

"a=b".partition("=") →
.partition(sep) Splits into 3-tuple: before, sep, after ("a","=","b")

"a=b=c".rpartition("=") →
.rpartition(sep) Like partition but from the right ("a=b","=","c")

▸ Formatting & Alignment


Method / Syntax What It Does Example
.center(width) Centers string in a field of given width "hi".center(10) → " hi "

.center(width, "hi".center(10,"*") →
Centers using a fill character
fill) "****hi****"

.ljust(width) Left-justifies in a field of given width "hi".ljust(10) → "hi "

.rjust(width) Right-justifies in a field of given width "hi".rjust(10) → " hi"

.zfill(width) Pads with zeros on the left "42".zfill(5) → "00042"

.expandtabs(n) Replaces tabs with n spaces (default "a\tb".expandtabs(4) → "a b"


8)

f-strings Embed expressions directly in strings f"2+2={2+2}" → "2+2=4"

.format() Insert values by index or name "{0} {1}".format("hi","there")

"Hi
.format_map(d) Like format() but uses a dictionary {name}".format_map({"name":"Ali"
})

▸ Encoding, Length & Slicing


Method / Syntax What It Does Example
"hello".encode("utf-8") →
.encode(enc) Encodes string to bytes b"hello"

.encode(enc, err) Encodes with error handling mode "hello".encode("ascii","ignore")

b"hello".decode("utf-8") →
[Link](enc) Decodes bytes back to string "hello"

len(s) Returns number of characters len("hello") → 5

s[i] Access character at index i "hello"[1] → "e"

s[i:j] Slice from i to j (j not included) "hello"[1:4] → "ell"

s[::n] Every nth character "hello"[::2] → "hlo"

s[::-1] Reverse a string "hello"[::-1] → "olleh"

🔢 INTEGER (int) METHODS & FUNCTIONS


💡 Integers have very few built-in methods. Most useful integer operations come from built-in functions like
abs(), pow(), divmod(), and number system converters.

▸ Methods & Built-in Functions


Method / Syntax What It Does Example
int(x) Converts x to integer int("42") → 42

int(x, base) Converts string in given base to int int("1010", 2) → 10

.bit_length() Number of bits needed to represent int (10).bit_length() → 4

.bit_count() Number of 1-bits in binary (Python (7).bit_count() → 3


3.10+)
(255).to_bytes(2,"big") →
.to_bytes(n, order) Converts int to bytes object b"\x00\xff"

int.from_bytes(b, int.from_bytes(b"\xff","big")
Converts bytes to int
order) → 255

.as_integer_ratio() Returns (numerator, denominator) (5).as_integer_ratio() →


tuple (5,1)

.conjugate() Returns complex conjugate (self for (3).conjugate() → 3


int)

abs(n) Returns absolute value abs(-7) → 7

pow(x, y) Returns x to the power y pow(2, 8) → 256

pow(x, y, mod) Returns (x**y) % mod efficiently pow(2, 10, 1000) → 24

divmod(x, y) Returns (quotient, remainder) tuple divmod(17, 5) → (3, 2)

bin(n) Converts int to binary string bin(10) → "0b1010"

oct(n) Converts int to octal string oct(8) → "0o10"

hex(n) Converts int to hexadecimal string hex(255) → "0xff"

round(n) Rounds to nearest integer round(3.7) → 4

isinstance(n, int) Checks if n is an integer isinstance(5, int) → True

▸ Arithmetic & Bitwise Operators


Method / Syntax What It Does Example
a + b Addition 3 + 4 → 7

a - b Subtraction 10 - 3 → 7

a * b Multiplication 3 * 4 → 12

a ** b Exponentiation (power) 2 ** 8 → 256

a / b Division (always returns float) 7 / 2 → 3.5

a // b Floor division (integer result) 7 // 2 → 3

a % b Modulo (remainder) 17 % 5 → 2

a & b Bitwise AND 5 & 3 → 1

a | b Bitwise OR 5 | 3 → 7
a ^ b Bitwise XOR 5 ^ 3 → 6

~a Bitwise NOT ~5 → -6

a << n Left bit shift 1 << 3 → 8

a >> n Right bit shift 8 >> 2 → 2

🔣 FLOAT METHODS & math MODULE FUNCTIONS

💡 Float has a few built-in methods. Most powerful operations come from the math module — always add
import math at the top of your file first.

▸ Float Methods & Math Functions


Method / Syntax What It Does Example
float(x) Converts x to float float("3.14") → 3.14

float("inf") Positive infinity float("inf") → inf

float("-inf") Negative infinity float("-inf") → -inf

float("nan") Not a Number float("nan") → nan

.is_integer() True if float has no fractional part (3.0).is_integer() → True

.is_integer() False if fractional part exists (3.5).is_integer() → False

.as_integer_ratio() Returns exact (numerator, (0.5).as_integer_ratio() →


denominator) (1,2)

(3.14).hex() →
.hex() Returns float as hex string "0x1.91eb851eb851fp+1"

[Link]("0x1.8p+0") →
[Link](s) Creates float from hex string 1.5

.conjugate() Returns complex conjugate (self for (3.14).conjugate() → 3.14


float)

round(f, n) Rounds to n decimal places round(3.14159, 2) → 3.14

abs(f) Absolute value of float abs(-3.14) → 3.14

[Link](f) Rounds down to nearest int [Link](3.9) → 3

[Link](f) Rounds up to nearest int [Link](3.1) → 4

[Link](f) Removes decimal part (towards zero) [Link](-3.9) → -3

[Link](f) Square root [Link](16.0) → 4.0

[Link](float("nan")) →
[Link](f) True if float is NaN True

[Link](float("inf")) →
[Link](f) True if float is infinity True

[Link](f) True if float is finite (not inf/nan) [Link](3.14) → True

[Link](f) Natural logarithm [Link](math.e) → 1.0


[Link](f, base) Logarithm with specified base [Link](100, 10) → 2.0

math.log2(f) Base-2 logarithm math.log2(8) → 3.0

math.log10(f) Base-10 logarithm math.log10(1000) → 3.0

⚡ QUICK TIPS FOR COMPETITIVE


PROGRAMMING

Most used string ops in CP: input().split() • "".join() • s[::-1] • [Link]()


Read a line of ints instantly: a, b = map(int, input().split())
Read a list of n ints: arr = list(map(int, input().split()))
Convert int ↔ string: str(42) → "42" int("42") → 42
Check if string is a number: [Link]() or [Link]()
Reverse a string: s[::-1]
Count vowels in a string: sum(1 for c in s if c in "aeiouAEIOU")
Most used int ops in CP: n % 2 == 0 (even check) • n // 2 (halve) • abs(n) •
pow(a,b,mod)
Most used float ops in CP: round(f, 2) • [Link]() • [Link]() •
[Link]()

Python Methods Reference • String · Integer · Float • Keep this open while coding 🐍

You might also like