0% found this document useful (0 votes)
19 views2 pages

Python Cheat Sheet Overview

This document provides a summary of common Python string, file, and date/time methods. It lists common string methods like capitalize(), count(), find(), lower(), replace(), split(), etc. It also lists common file methods like close(), flush(), read(), seek(), tell(), write(), etc. Finally, it lists common date/time methods in Python like date(), datetime(), replace(), strftime(), time(), timezone(), weekday(), etc.

Uploaded by

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

Python Cheat Sheet Overview

This document provides a summary of common Python string, file, and date/time methods. It lists common string methods like capitalize(), count(), find(), lower(), replace(), split(), etc. It also lists common file methods like close(), flush(), read(), seek(), tell(), write(), etc. Finally, it lists common date/time methods in Python like date(), datetime(), replace(), strftime(), time(), timezone(), weekday(), etc.

Uploaded by

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

15/09/2022, 15:11 Python Cheat Sheet | OverAPI.

com

[Link] Python jQuery NodeJS PHP Java Ruby Javascript ActionScript CSS Express More » Search

Resource String File Set & D


Online
Official Website
String Methods
capitalize()
Methods
close()
Mapping Date Obje
replace((yea
[Link] center(width[, fillchar]) flush() Set Types timetuple()
count(sub[, start[, end]]) fileno() len(s) toordinal()
Download decode isatty() x in s weekday()()
Python Quick Reference Card [. encode([encoding[, errors]]) next() isoweekday
x not in s
pdf] endswith(suffix[, start[, end]]) read([size]) isocalendar(
isdisjoint(other)
Python 2.6 Quick Reference expandtabs([tabsize]) readline([size]) isoformat()
issubset(others)
find(sub[, start[, end]]) readlines([sizehint]) __str__()
issuperset
Related format(*args, **kwargs) xreadlines() ctime()
union(other...)
Django index(sub[, start[, end]]) seek(offset[, whence]) strftime()
intersection(other, ...)
isalnum() tell()
difference(other...)
isalpha() truncate([size])
symmetric_difference(other) Datetime
isdigit() write(str) date()
copy()
islower() writelines(sequence) time()
update()
isspace() timetz()
Math istitle() Attributes
intersection_update()
difference_update() replace([yea
isupper() closed ur[, minute[,
symmetric_difference_update()
Number Theoretic join(iterable) encoding add(elem) ond[, tzinfo]
ceil(x) ljust(width[, fillchar]) errors astimezone(
remove()
copysign(x,y) lower() mode utcoffset()
discard(elem)
fabs(x) lstrip([chars]) name dst()
pop()
factorial(x) partition(sep) newlines tzname()
clear()
floor(x) replace(old, new[, count]) softspace timetuple()
fmod(x,y) rfind(sub[, start[, end]]) utctimetuple
frexp(x) rindex(sub[, start[, end]]) Mapping Types
toordinal()
fsum(iterable) rjust(width[, fillchar]) len(d) weekday()
isinf(x) rpartition(sep) d[key] isoweekday
isnan(x) rsplit([sep[, maxsplit]]) d[key] = value isocalendar(
rstrip([chars])
ldexp(x,i)
modf() split([sep[, maxsplit]]) Random del d[key]
key in d
isoformat()
__str__()
trunc() splitlines([keepends]) key not in d ctime()
startswith(prefix[, start[, end]]) Functions strftime()
seed([x]) iter(d)
Power and Logarithmic strip([chars])
getstate() clear()
exp(x) swapcase Time Obje
setstate(state) copy()
log(x[,base]) title() replace([hou
jumpahead(n) fromkeys(seq[, value])
log1p(x) translate(table[, deletechars]) [, microseco
getrandbits(k) get(key[, default])
log10(x) upper() isoformat()
randrange([start], stop[, step]) has_key(key)
pow(x,y) zfill(width) __str__()
randint(a,b) items()
sqrt(x) isnumeric() strftime()
choice(seq) iteritems()
isdecimal() utcoffset()
shuffle(x[,random]) iterkeys()
Trigonometric Functions itervalues() dst()
acos(x) sample(population,k) tzname()
random() keys()
asin(x) pop(key[, default])
atan(x) uniform(a,b)
triangular(low,high,mode) popitem()
atan2(y,x) setdefault(key[, default])
cos(x) betavariate(alpha,beta)
expovariate(lambd) update([other])
hypot(x,y)
sin(x) OS gammavariate(alpha,beta) values

tan(x) gauss(mu,sigma)
os Variables lognormvariate(mu,sigma)
altsep normalvariate(mu,sigma)
Angular Conversion vonmisesvariate(mu,kappa)
degrees(x)
Alternative sep Special M
curdir paretovariate(alpha) __new__(c
radians(x) weibullvariate(alpha,beta)
Current dir string __lt__(self,
Hyperbolic Functions defpath
Default search path
String __init__(se
acosh(x) __le__(self
asinh(x)
atanh(x)
devnull
Path of null device
Formatting __del__(se
extsep __gt__(self
cosh(x) Formatting Operations
sinh(x) Extension separator
linesep
Date 'd'
__repr__(s
__ge__(sel
tanh(x) Signed integer decimal.
Line separator
name
Formatting 'i'
__str__(sel
__eq__(sel
Constants Signed integer decimal.
[Link]
Name of OS
Date Formatting 'o' __cmp__(s
The mathematical constant π = pardir %a Signed octal value. __ne__(sel
3.141592..., to available precisi Parent dir string __index__(
Abbreviated weekday (Sun) 'u'
on. pathsep %A Obsolete type – it is identical to __nonzero
math.e Patch separator
Weekday (Sunday) 'd'. __hash__(s
The mathematical constant e = sep %b 'x'
Path separator
__getattr__
2.718281..., to available precisi Abbreviated month name (Jan) Signed hexadecimal (lowercas
on. __getattrib
%B e).
__setattr__
Month name (January) 'X' __delattr__
%c Signed hexadecimal (uppercas
e). __call__(se
Date and time
%d 'e'
Day (leading zeros) (01 to 31) Floating point exponential form
%H at (lowercase).
24 hour (leading zeros) (00 to 2 'E'
3) Floating point exponential form
%I at (uppercase).
12 hour (leading zeros) (01 to 1 'f'
2) Floating point decimal format.
%j 'F'
Day of year (001 to 366) Floating point decimal format.
%m 'g'
Month (01 to 12) Floating point format. Uses low
%M ercase exponential format if exp
Shop Nowis less than -4 or not less
onent
Minute (00 to 59)

[Link] 1/2
15/09/2022, 15:11 Python Cheat Sheet | [Link]
%p than precision, decimal format
[Link] Python jQuery NodeJS PHP Java Ruby Javascript ActionScript
AM or PM CSS Express More » Search
otherwise.
%S 'G'
Second (00 to 61?) Floating point format. Uses upp
%U ercase exponential format if exp
Week number1 (00 to 53) onent is less than -4 or not less
than precision, decimal format
%w otherwise.
Weekday2 (0 to 6)
'c'
%W Single character (accepts integ
Week number3 (00 to 53) er or single character string).
%x 'r'
Date String (converts any Python obj
%X ect using repr().
Time 's'
%y String (converts any Python obj
Year without century (00 to 99) ect using str()
%Y '%'
Year (2008) No argument is converted, resul
%Z ts in a '%' character in the resul
Time zone (GMT) t.
%%
A literal "%" character (%)

Shop Now

[Link] 2/2

Common questions

Powered by AI

`math.frexp()` in Python decomposes a floating-point number into its mantissa and exponent, representing the number as `x = mantissa * 2**exponent` . This function is particularly useful in numerical computations that require an understanding of the floating-point representation, such as precision analysis or when implementing logarithmic calculations manually.

`random.shuffle()` and `random.sample()` serve different purposes in random module functions. `random.shuffle()` is used to randomly reorder elements in a list in place , meaning it alters the original list directly. In contrast, `random.sample()` creates a new list containing a specified number of randomly selected elements from the original iterable but does not modify the original list . These functions are useful for tasks such as randomizing presentation orders or selecting random choices without repetitions.

In Python, `math.isinf()` and `math.isnan()` serve to assess special floating-point values. `math.isinf()` checks whether a number is infinite (either positive or negative) and returns `True` if it is . On the other hand, `math.isnan()` checks if a value is NaN (Not a Number) and returns `True` for such inputs . Both are crucial for handling extreme or undefined values, typical in scientific computations.

The `expandtabs()` string method in Python replaces tab characters (`\t`) in a string with spaces, each tab character being replaced by the number of spaces to the next tab stop . It is essential in text formatting where aligning text into columns is required, as it allows for consistent spacing regardless of tab character variations used across different environments or text editors.

In Python, `flush()` is used in file handling to forcefully write buffered output to the underlying file system, ensuring that all data is physically stored . This is typically necessary when some data needs to be frequently updated or shared files need to be read by other programs. Conversely, `seek()` is used to move the file pointer to a specified location within the file . It allows accessing or reading specific parts of a file without having to process the entire file, which is useful for handling large files efficiently.

`dict.get()` provides a safer way to access dictionary elements, allowing a default return value if the key does not exist . This prevents KeyErrors and facilitates program flow. In contrast, direct indexing (`dict[key]`) raises a KeyError if the key is absent, necessitating error handling . Using `get()` enhances code reliability when dealing with optional keys.

In cross-platform Python programming, using `os.sep` and `os.altsep` can handle platform-specific path separators . `os.sep` is the primary separator used by the operating system (e.g., '\\' for Windows, '/' for Unix-based systems). `os.altsep` provides an alternative when a system allows multiple separators (e.g., Windows also recognizing '/'). Utilizing these ensures compatibility and reduces errors in file path handling across different operating systems.

`ctime()` is used to convert a time expressed in seconds since the epoch to a readable string, providing a simplified way to output current time . Conversely, `strftime()` formats a provided date and time according to directives in format strings, offering flexibility in representation . While `ctime()` is used for direct conversion, `strftime()` allows detailed and customized formatting of date-time data.

Python provides several string methods to modify character case, including `capitalize()`, which capitalizes the first character of a string and lowers the rest ; `lower()`, which converts all characters in a string to lowercase ; `upper()`, which converts all characters to uppercase ; `swapcase()`, which swaps the case of all characters in the string ; and `title()`, which capitalizes the first letter of each word in the string . Each method targets different formatting needs for string manipulation.

The `symmetrical_difference()` method returns a new set containing elements that are in either of the initial sets but not in their intersection . It essentially captures differences between two sets. Conversely, `union()` returns a set containing all distinct elements from both sets, effectively merging them . While `union()` is used for combining data sets, `symmetrical_difference()` highlights differences, aiding in comparative analysis.

You might also like