doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
stat.S_ISGID
Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT). | python.library.stat#stat.S_ISGID |
stat.S_ISLNK(mode)
Return non-zero if the mode is from a symbolic link. | python.library.stat#stat.S_ISLNK |
stat.S_ISPORT(mode)
Return non-zero if the mode is from an event port. New in version 3.4. | python.library.stat#stat.S_ISPORT |
stat.S_ISREG(mode)
Return non-zero if the mode is from a regular file. | python.library.stat#stat.S_ISREG |
stat.S_ISSOCK(mode)
Return non-zero if the mode is from a socket. | python.library.stat#stat.S_ISSOCK |
stat.S_ISUID
Set UID bit. | python.library.stat#stat.S_ISUID |
stat.S_ISVTX
Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process. | python.library.stat#stat.S_ISVTX |
stat.S_ISWHT(mode)
Return non-zero if the mode is from a whiteout. New in version 3.4. | python.library.stat#stat.S_ISWHT |
stat.S_IWGRP
Group has write permission. | python.library.stat#stat.S_IWGRP |
stat.S_IWOTH
Others have write permission. | python.library.stat#stat.S_IWOTH |
stat.S_IWRITE
Unix V7 synonym for S_IWUSR. | python.library.stat#stat.S_IWRITE |
stat.S_IWUSR
Owner has write permission. | python.library.stat#stat.S_IWUSR |
stat.S_IXGRP
Group has execute permission. | python.library.stat#stat.S_IXGRP |
stat.S_IXOTH
Others have execute permission. | python.library.stat#stat.S_IXOTH |
stat.S_IXUSR
Owner has execute permission. | python.library.stat#stat.S_IXUSR |
stat.UF_APPEND
The file may only be appended to. | python.library.stat#stat.UF_APPEND |
stat.UF_COMPRESSED
The file is stored compressed (Mac OS X 10.6+). | python.library.stat#stat.UF_COMPRESSED |
stat.UF_HIDDEN
The file should not be displayed in a GUI (Mac OS X 10.5+). | python.library.stat#stat.UF_HIDDEN |
stat.UF_IMMUTABLE
The file may not be changed. | python.library.stat#stat.UF_IMMUTABLE |
stat.UF_NODUMP
Do not dump the file. | python.library.stat#stat.UF_NODUMP |
stat.UF_NOUNLINK
The file may not be renamed or deleted. | python.library.stat#stat.UF_NOUNLINK |
stat.UF_OPAQUE
The directory is opaque when viewed through a union stack. | python.library.stat#stat.UF_OPAQUE |
@staticmethod
Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C:
@staticmethod
def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator – see Function definitions for details. A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors. Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom: class C:
builtin_open = staticmethod(open)
For more information on static methods, see The standard type hierarchy. | python.library.functions#staticmethod |
statistics — Mathematical statistics functions New in version 3.4. Source code: Lib/statistics.py This module provides functions for calculating mathematical statistics of numeric (Real-valued) data. The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators. Unless explicitly noted, these functions support int, float, Decimal and Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data). Averages and measures of central location These functions calculate an average or typical value from a population or sample.
mean() Arithmetic mean (“average”) of data.
fmean() Fast, floating point arithmetic mean.
geometric_mean() Geometric mean of data.
harmonic_mean() Harmonic mean of data.
median() Median (middle value) of data.
median_low() Low median of data.
median_high() High median of data.
median_grouped() Median, or 50th percentile, of grouped data.
mode() Single mode (most common value) of discrete or nominal data.
multimode() List of modes (most common values) of discrete or nomimal data.
quantiles() Divide data into intervals with equal probability. Measures of spread These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.
pstdev() Population standard deviation of data.
pvariance() Population variance of data.
stdev() Sample standard deviation of data.
variance() Sample variance of data. Function details Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.
statistics.mean(data)
Return the sample arithmetic mean of data which can be a sequence or iterable. The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data. If data is empty, StatisticsError will be raised. Some examples of use: >>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
Note The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust measures of central location, see median() and mode(). The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.
statistics.fmean(data)
Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25])
4.25
New in version 3.8.
statistics.geometric_mean(data)
Convert data to floats and compute the geometric mean. The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum). Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable. No special efforts are made to achieve exact results. (However, this may change in the future.) >>> round(geometric_mean([54, 24, 36]), 1)
36.0
New in version 3.8.
statistics.harmonic_mean(data)
Return the harmonic mean of data, a sequence or iterable of real-valued numbers. The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero. The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging rates or ratios, for example speeds. Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed? >>> harmonic_mean([40, 60])
48.0
Suppose an investor purchases an equal value of shares in each of three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. What is the average P/E ratio for the investor’s portfolio? >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
3.6
StatisticsError is raised if data is empty, or any element is less than zero. The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.) New in version 3.6.
statistics.median(data)
Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The median is a robust measure of central location and is less affected by the presence of outliers. When the number of data points is odd, the middle data point is returned: >>> median([1, 3, 5])
3
When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5, 7])
4.0
This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point. If the data is ordinal (supports order operations) but not numeric (doesn’t support addition), consider using median_low() or median_high() instead.
statistics.median_low(data)
Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned. >>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3
Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.
statistics.median_high(data)
Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. >>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5
Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.
statistics.median_grouped(data, interval=1)
Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterable. >>> median_grouped([52, 52, 53, 54])
52.5
In the following example, the data are rounded, so that each value represents the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2 is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the data given, the middle value falls somewhere in the class 3.5–4.5, and interpolation is used to estimate it: >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7
Optional argument interval represents the class interval, and defaults to 1. Changing the class interval naturally will change the interpolation: >>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5
This function does not check whether the data points are at least interval apart. CPython implementation detail: Under some circumstances, median_grouped() may coerce data points to floats. This behaviour is likely to change in the future. See also “Statistics for the Behavioral Sciences”, Frederick J Gravetter and Larry B Wallnau (8th Edition). The SSMEDIAN function in the Gnome Gnumeric spreadsheet, including this discussion.
statistics.mode(data)
Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location. If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised. mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data: >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found.
statistics.multimode(data)
Return a list of the most frequently occurring values in the order they were first encountered in the data. Will return more than one result if there are multiple modes or an empty list if the data is empty: >>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('')
[]
New in version 3.8.
statistics.pstdev(data, mu=None)
Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251
statistics.pvariance(data, mu=None)
Return the population variance of data, a non-empty sequence or iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. If the optional second argument mu is given, it is typically the mean of the data. It can also be used to compute the second moment around a point that is not the mean. If it is missing or None (the default), the arithmetic mean is automatically calculated. Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice. Raises StatisticsError if data is empty. Examples: >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25
If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation: >>> mu = mean(data)
>>> pvariance(data, mu)
1.25
Decimals and Fractions are supported: >>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')
>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)
Note When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom. If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are a random sample of the population, the result will be an unbiased estimate of the population variance.
statistics.stdev(data, xbar=None)
Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
statistics.variance(data, xbar=None)
Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. If the optional second argument xbar is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated. Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance(). Raises StatisticsError if data has fewer than two values. Examples: >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095
If you have already calculated the mean of your data, you can pass it as the optional second argument xbar to avoid recalculation: >>> m = mean(data)
>>> variance(data, m)
1.3720238095238095
This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results. Decimal and Fraction values are supported: >>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')
>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)
Note This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance. If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample.
statistics.quantiles(data, *, n=4, method='exclusive')
Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate data into 100 equal sized groups. Raises StatisticsError if n is not least 1. The data can be any iterable containing sample data. For meaningful results, the number of data points in data should be larger than n. Raises StatisticsError if there are not at least two data points. The cut points are linearly interpolated from the two nearest data points. For example, if a cut point falls one-third of the distance between two sample values, 100 and 112, the cut-point will evaluate to 104. The method for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population. The default method is “exclusive” and is used for data sampled from a population that can have more extreme values than found in the samples. The portion of the population falling below the i-th of m sorted data points is computed as i / (m + 1). Given nine sample values, the method sorts them and assigns the following percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%. Setting the method to “inclusive” is used for describing population data or for samples that are known to include the most extreme values from the population. The minimum value in data is treated as the 0th percentile and the maximum value is treated as the 100th percentile. The portion of the population falling below the i-th of m sorted data points is computed as (i - 1) / (m - 1). Given 11 sample values, the method sorts them and assigns the following percentiles: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%. # Decile cut points for empirically sampled data
>>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
... 100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
... 106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
... 111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
... 103, 107, 101, 81, 109, 104]
>>> [round(q, 1) for q in quantiles(data, n=10)]
[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]
New in version 3.8.
Exceptions A single exception is defined:
exception statistics.StatisticsError
Subclass of ValueError for statistics-related exceptions.
NormalDist objects NormalDist is a tool for creating and manipulating normal distributions of a random variable. It is a class that treats the mean and standard deviation of data measurements as a single entity. Normal distributions arise from the Central Limit Theorem and have a wide range of applications in statistics.
class statistics.NormalDist(mu=0.0, sigma=1.0)
Returns a new NormalDist object where mu represents the arithmetic mean and sigma represents the standard deviation. If sigma is negative, raises StatisticsError.
mean
A read-only property for the arithmetic mean of a normal distribution.
median
A read-only property for the median of a normal distribution.
mode
A read-only property for the mode of a normal distribution.
stdev
A read-only property for the standard deviation of a normal distribution.
variance
A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.
classmethod from_samples(data)
Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev(). The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.
samples(n, *, seed=None)
Generates n random samples for a given mean and standard deviation. Returns a list of float values. If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.
pdf(x)
Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero. The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.
cdf(x)
Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).
inv_cdf(p)
Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p. Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.
overlap(other)
Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.
quantiles(n=4)
Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.
zscore(x)
Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev. New in version 3.9.
Instances of NormalDist support addition, subtraction, multiplication and division by a constant. These operations are used for translation and scaling. For example: >>> temperature_february = NormalDist(5, 2.5) # Celsius
>>> temperature_february * (9/5) + 32 # Fahrenheit
NormalDist(mu=41.0, sigma=4.5)
Dividing a constant by an instance of NormalDist is not supported because the result wouldn’t be normally distributed. Since normal distributions arise from additive effects of independent variables, it is possible to add and subtract two independent normally distributed random variables represented as instances of NormalDist. For example: >>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
>>> drug_effects = NormalDist(0.4, 0.15)
>>> combined = birth_weights + drug_effects
>>> round(combined.mean, 1)
3.1
>>> round(combined.stdev, 1)
0.5
New in version 3.8.
NormalDist Examples and Recipes NormalDist readily solves classic probability problems. For example, given historical data for SAT exams showing that scores are normally distributed with a mean of 1060 and a standard deviation of 195, determine the percentage of students with test scores between 1100 and 1200, after rounding to the nearest whole number: >>> sat = NormalDist(1060, 195)
>>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
>>> round(fraction * 100.0, 1)
18.4
Find the quartiles and deciles for the SAT scores: >>> list(map(round, sat.quantiles()))
[928, 1060, 1192]
>>> list(map(round, sat.quantiles(n=10)))
[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]
To estimate the distribution for a model than isn’t easy to solve analytically, NormalDist can generate input samples for a Monte Carlo simulation: >>> def model(x, y, z):
... return (3*x + 7*x*y - 5*y) / (11 * z)
...
>>> n = 100_000
>>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)
>>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)
>>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)
>>> quantiles(map(model, X, Y, Z))
[1.4591308524824727, 1.8035946855390597, 2.175091447274739]
Normal distributions can be used to approximate Binomial distributions when the sample size is large and when the probability of a successful trial is near 50%. For example, an open source conference has 750 attendees and two rooms with a 500 person capacity. There is a talk about Python and another about Ruby. In previous conferences, 65% of the attendees preferred to listen to Python talks. Assuming the population preferences haven’t changed, what is the probability that the Python room will stay within its capacity limits? >>> n = 750 # Sample size
>>> p = 0.65 # Preference for Python
>>> q = 1.0 - p # Preference for Ruby
>>> k = 500 # Room capacity
>>> # Approximation using the cumulative normal distribution
>>> from math import sqrt
>>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)
0.8402
>>> # Solution using the cumulative binomial distribution
>>> from math import comb, fsum
>>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)
0.8402
>>> # Approximation using a simulation
>>> from random import seed, choices
>>> seed(8675309)
>>> def trial():
... return choices(('Python', 'Ruby'), (p, q), k=n).count('Python')
>>> mean(trial() <= k for i in range(10_000))
0.8398
Normal distributions commonly arise in machine learning problems. Wikipedia has a nice example of a Naive Bayesian Classifier. The challenge is to predict a person’s gender from measurements of normally distributed features including height, weight, and foot size. We’re given a training dataset with measurements for eight people. The measurements are assumed to be normally distributed, so we summarize the data with NormalDist: >>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])
>>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])
>>> weight_male = NormalDist.from_samples([180, 190, 170, 165])
>>> weight_female = NormalDist.from_samples([100, 150, 130, 150])
>>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])
>>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])
Next, we encounter a new person whose feature measurements are known but whose gender is unknown: >>> ht = 6.0 # height
>>> wt = 130 # weight
>>> fs = 8 # foot size
Starting with a 50% prior probability of being male or female, we compute the posterior as the prior times the product of likelihoods for the feature measurements given the gender: >>> prior_male = 0.5
>>> prior_female = 0.5
>>> posterior_male = (prior_male * height_male.pdf(ht) *
... weight_male.pdf(wt) * foot_size_male.pdf(fs))
>>> posterior_female = (prior_female * height_female.pdf(ht) *
... weight_female.pdf(wt) * foot_size_female.pdf(fs))
The final prediction goes to the largest posterior. This is known as the maximum a posteriori or MAP: >>> 'male' if posterior_male > posterior_female else 'female'
'female' | python.library.statistics |
statistics.fmean(data)
Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25])
4.25
New in version 3.8. | python.library.statistics#statistics.fmean |
statistics.geometric_mean(data)
Convert data to floats and compute the geometric mean. The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum). Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable. No special efforts are made to achieve exact results. (However, this may change in the future.) >>> round(geometric_mean([54, 24, 36]), 1)
36.0
New in version 3.8. | python.library.statistics#statistics.geometric_mean |
statistics.harmonic_mean(data)
Return the harmonic mean of data, a sequence or iterable of real-valued numbers. The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero. The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging rates or ratios, for example speeds. Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed? >>> harmonic_mean([40, 60])
48.0
Suppose an investor purchases an equal value of shares in each of three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. What is the average P/E ratio for the investor’s portfolio? >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
3.6
StatisticsError is raised if data is empty, or any element is less than zero. The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.) New in version 3.6. | python.library.statistics#statistics.harmonic_mean |
statistics.mean(data)
Return the sample arithmetic mean of data which can be a sequence or iterable. The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data. If data is empty, StatisticsError will be raised. Some examples of use: >>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
Note The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust measures of central location, see median() and mode(). The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ. | python.library.statistics#statistics.mean |
statistics.median(data)
Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The median is a robust measure of central location and is less affected by the presence of outliers. When the number of data points is odd, the middle data point is returned: >>> median([1, 3, 5])
3
When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5, 7])
4.0
This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point. If the data is ordinal (supports order operations) but not numeric (doesn’t support addition), consider using median_low() or median_high() instead. | python.library.statistics#statistics.median |
statistics.median_grouped(data, interval=1)
Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterable. >>> median_grouped([52, 52, 53, 54])
52.5
In the following example, the data are rounded, so that each value represents the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2 is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the data given, the middle value falls somewhere in the class 3.5–4.5, and interpolation is used to estimate it: >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7
Optional argument interval represents the class interval, and defaults to 1. Changing the class interval naturally will change the interpolation: >>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5
This function does not check whether the data points are at least interval apart. CPython implementation detail: Under some circumstances, median_grouped() may coerce data points to floats. This behaviour is likely to change in the future. See also “Statistics for the Behavioral Sciences”, Frederick J Gravetter and Larry B Wallnau (8th Edition). The SSMEDIAN function in the Gnome Gnumeric spreadsheet, including this discussion. | python.library.statistics#statistics.median_grouped |
statistics.median_high(data)
Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. >>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5
Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated. | python.library.statistics#statistics.median_high |
statistics.median_low(data)
Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterable. The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned. >>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3
Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated. | python.library.statistics#statistics.median_low |
statistics.mode(data)
Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location. If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised. mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data: >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found. | python.library.statistics#statistics.mode |
statistics.multimode(data)
Return a list of the most frequently occurring values in the order they were first encountered in the data. Will return more than one result if there are multiple modes or an empty list if the data is empty: >>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('')
[]
New in version 3.8. | python.library.statistics#statistics.multimode |
class statistics.NormalDist(mu=0.0, sigma=1.0)
Returns a new NormalDist object where mu represents the arithmetic mean and sigma represents the standard deviation. If sigma is negative, raises StatisticsError.
mean
A read-only property for the arithmetic mean of a normal distribution.
median
A read-only property for the median of a normal distribution.
mode
A read-only property for the mode of a normal distribution.
stdev
A read-only property for the standard deviation of a normal distribution.
variance
A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.
classmethod from_samples(data)
Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev(). The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.
samples(n, *, seed=None)
Generates n random samples for a given mean and standard deviation. Returns a list of float values. If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.
pdf(x)
Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero. The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.
cdf(x)
Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).
inv_cdf(p)
Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p. Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.
overlap(other)
Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.
quantiles(n=4)
Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.
zscore(x)
Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev. New in version 3.9.
Instances of NormalDist support addition, subtraction, multiplication and division by a constant. These operations are used for translation and scaling. For example: >>> temperature_february = NormalDist(5, 2.5) # Celsius
>>> temperature_february * (9/5) + 32 # Fahrenheit
NormalDist(mu=41.0, sigma=4.5)
Dividing a constant by an instance of NormalDist is not supported because the result wouldn’t be normally distributed. Since normal distributions arise from additive effects of independent variables, it is possible to add and subtract two independent normally distributed random variables represented as instances of NormalDist. For example: >>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
>>> drug_effects = NormalDist(0.4, 0.15)
>>> combined = birth_weights + drug_effects
>>> round(combined.mean, 1)
3.1
>>> round(combined.stdev, 1)
0.5
New in version 3.8. | python.library.statistics#statistics.NormalDist |
cdf(x)
Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x). | python.library.statistics#statistics.NormalDist.cdf |
classmethod from_samples(data)
Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev(). The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion. | python.library.statistics#statistics.NormalDist.from_samples |
inv_cdf(p)
Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p. Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p. | python.library.statistics#statistics.NormalDist.inv_cdf |
mean
A read-only property for the arithmetic mean of a normal distribution. | python.library.statistics#statistics.NormalDist.mean |
median
A read-only property for the median of a normal distribution. | python.library.statistics#statistics.NormalDist.median |
mode
A read-only property for the mode of a normal distribution. | python.library.statistics#statistics.NormalDist.mode |
overlap(other)
Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions. | python.library.statistics#statistics.NormalDist.overlap |
pdf(x)
Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero. The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0. | python.library.statistics#statistics.NormalDist.pdf |
quantiles(n=4)
Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups. | python.library.statistics#statistics.NormalDist.quantiles |
samples(n, *, seed=None)
Generates n random samples for a given mean and standard deviation. Returns a list of float values. If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context. | python.library.statistics#statistics.NormalDist.samples |
stdev
A read-only property for the standard deviation of a normal distribution. | python.library.statistics#statistics.NormalDist.stdev |
variance
A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation. | python.library.statistics#statistics.NormalDist.variance |
zscore(x)
Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev. New in version 3.9. | python.library.statistics#statistics.NormalDist.zscore |
statistics.pstdev(data, mu=None)
Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251 | python.library.statistics#statistics.pstdev |
statistics.pvariance(data, mu=None)
Return the population variance of data, a non-empty sequence or iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. If the optional second argument mu is given, it is typically the mean of the data. It can also be used to compute the second moment around a point that is not the mean. If it is missing or None (the default), the arithmetic mean is automatically calculated. Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice. Raises StatisticsError if data is empty. Examples: >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25
If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation: >>> mu = mean(data)
>>> pvariance(data, mu)
1.25
Decimals and Fractions are supported: >>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')
>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)
Note When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom. If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are a random sample of the population, the result will be an unbiased estimate of the population variance. | python.library.statistics#statistics.pvariance |
statistics.quantiles(data, *, n=4, method='exclusive')
Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate data into 100 equal sized groups. Raises StatisticsError if n is not least 1. The data can be any iterable containing sample data. For meaningful results, the number of data points in data should be larger than n. Raises StatisticsError if there are not at least two data points. The cut points are linearly interpolated from the two nearest data points. For example, if a cut point falls one-third of the distance between two sample values, 100 and 112, the cut-point will evaluate to 104. The method for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population. The default method is “exclusive” and is used for data sampled from a population that can have more extreme values than found in the samples. The portion of the population falling below the i-th of m sorted data points is computed as i / (m + 1). Given nine sample values, the method sorts them and assigns the following percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%. Setting the method to “inclusive” is used for describing population data or for samples that are known to include the most extreme values from the population. The minimum value in data is treated as the 0th percentile and the maximum value is treated as the 100th percentile. The portion of the population falling below the i-th of m sorted data points is computed as (i - 1) / (m - 1). Given 11 sample values, the method sorts them and assigns the following percentiles: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%. # Decile cut points for empirically sampled data
>>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
... 100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
... 106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
... 111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
... 103, 107, 101, 81, 109, 104]
>>> [round(q, 1) for q in quantiles(data, n=10)]
[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]
New in version 3.8. | python.library.statistics#statistics.quantiles |
exception statistics.StatisticsError
Subclass of ValueError for statistics-related exceptions. | python.library.statistics#statistics.StatisticsError |
statistics.stdev(data, xbar=None)
Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827 | python.library.statistics#statistics.stdev |
statistics.variance(data, xbar=None)
Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. If the optional second argument xbar is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated. Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance(). Raises StatisticsError if data has fewer than two values. Examples: >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095
If you have already calculated the mean of your data, you can pass it as the optional second argument xbar to avoid recalculation: >>> m = mean(data)
>>> variance(data, m)
1.3720238095238095
This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results. Decimal and Fraction values are supported: >>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')
>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)
Note This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance. If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample. | python.library.statistics#statistics.variance |
exception StopAsyncIteration
Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration. New in version 3.5. | python.library.exceptions#StopAsyncIteration |
exception StopIteration
Raised by built-in function next() and an iterator’s __next__() method to signal that there are no further items produced by the iterator. The exception object has a single attribute value, which is given as an argument when constructing the exception, and defaults to None. When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception. If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception’s cause). Changed in version 3.3: Added value attribute and the ability for generator functions to use it to return a value. Changed in version 3.5: Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479. Changed in version 3.7: Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError. | python.library.exceptions#StopIteration |
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
Return a str version of object. See str() for details. str is the built-in string class. For general information about strings, see Text Sequence Type — str. | python.library.functions#str |
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows. If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object). If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects. Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example: >>> str(b'Zoot!')
"b'Zoot!'"
For more information on the str class and its methods, see Text Sequence Type — str and the String Methods section below. To output formatted strings, see the Formatted string literals and Format String Syntax sections. In addition, see the Text Processing Services section. | python.library.stdtypes#str |
str.capitalize()
Return a copy of the string with its first character capitalized and the rest lowercased. Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character. | python.library.stdtypes#str.capitalize |
str.casefold()
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss". The casefolding algorithm is described in section 3.13 of the Unicode Standard. New in version 3.3. | python.library.stdtypes#str.casefold |
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s). | python.library.stdtypes#str.center |
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. | python.library.stdtypes#str.count |
str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings. By default, the errors argument is not checked for best performances, but only used at the first encoding error. Enable the Python Development Mode, or use a debug build to check errors. Changed in version 3.1: Support for keyword arguments added. Changed in version 3.9: The errors is now checked in development mode and in debug mode. | python.library.stdtypes#str.encode |
str.endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. | python.library.stdtypes#str.endswith |
str.expandtabs(tabsize=8)
Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed. >>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234' | python.library.stdtypes#str.expandtabs |
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. Note The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator: >>> 'Py' in 'Python'
True | python.library.stdtypes#str.find |
str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. >>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
See Format String Syntax for a description of the various formatting options that can be specified in format strings. Note When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: '{:n}'.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads. Changed in version 3.7: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases. | python.library.stdtypes#str.format |
str.format_map(mapping)
Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass: >>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'
New in version 3.2. | python.library.stdtypes#str.format_map |
str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found. | python.library.stdtypes#str.index |
str.isalnum()
Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric(). | python.library.stdtypes#str.isalnum |
str.isalpha()
Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard. | python.library.stdtypes#str.isalpha |
str.isascii()
Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F. New in version 3.7. | python.library.stdtypes#str.isascii |
str.isdecimal()
Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”. | python.library.stdtypes#str.isdecimal |
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal. | python.library.stdtypes#str.isdigit |
str.isidentifier()
Return True if the string is a valid identifier according to the language definition, section Identifiers and keywords. Call keyword.iskeyword() to test whether string s is a reserved identifier, such as def and class. Example: >>> from keyword import iskeyword
>>> 'hello'.isidentifier(), iskeyword('hello')
True, False
>>> 'def'.isidentifier(), iskeyword('def')
True, True | python.library.stdtypes#str.isidentifier |
str.islower()
Return True if all cased characters 4 in the string are lowercase and there is at least one cased character, False otherwise. | python.library.stdtypes#str.islower |
str.isnumeric()
Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. | python.library.stdtypes#str.isnumeric |
str.isprintable()
Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.) | python.library.stdtypes#str.isprintable |
str.isspace()
Return True if there are only whitespace characters in the string and there is at least one character, False otherwise. A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S. | python.library.stdtypes#str.isspace |
str.istitle()
Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. | python.library.stdtypes#str.istitle |
str.isupper()
Return True if all cased characters 4 in the string are uppercase and there is at least one cased character, False otherwise. >>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False | python.library.stdtypes#str.isupper |
str.join(iterable)
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. | python.library.stdtypes#str.join |
str.ljust(width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s). | python.library.stdtypes#str.ljust |
str.lower()
Return a copy of the string with all the cased characters 4 converted to lowercase. The lowercasing algorithm used is described in section 3.13 of the Unicode Standard. | python.library.stdtypes#str.lower |
str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example: >>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!' | python.library.stdtypes#str.lstrip |
static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. | python.library.stdtypes#str.maketrans |
str.partition(sep)
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. | python.library.stdtypes#str.partition |
str.removeprefix(prefix, /)
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string: >>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
New in version 3.9. | python.library.stdtypes#str.removeprefix |
str.removesuffix(suffix, /)
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string: >>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
New in version 3.9. | python.library.stdtypes#str.removesuffix |
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. | python.library.stdtypes#str.replace |
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. | python.library.stdtypes#str.rfind |
str.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the substring sub is not found. | python.library.stdtypes#str.rindex |
str.rjust(width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s). | python.library.stdtypes#str.rjust |
str.rpartition(sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself. | python.library.stdtypes#str.rpartition |
str.rsplit(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below. | python.library.stdtypes#str.rsplit |
str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty' | python.library.stdtypes#str.rstrip |
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. For example: >>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example: >>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3'] | python.library.stdtypes#str.split |
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.
Representation Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation
\f or \x0c Form Feed
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator Changed in version 3.2: \v and \f added to list of line boundaries. For example: >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']
For comparison, split('\n') gives: >>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', ''] | python.library.stdtypes#str.splitlines |
str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. | python.library.stdtypes#str.startswith |
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example: >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32' | python.library.stdtypes#str.strip |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.