# String Methods
Python’s string type provides many functions that act on the capitalization of a string. These include :
With unicode strings (the default in Python 3), these operations are not 1:1 mappings or reversible. Most of these operations are intended for display purposes, rather than normalization.
str.casefold creates a lowercase string that is suitable for case insensitive comparisons. This is more aggressive than str.lower and may modify strings that are already in lowercase or cause strings to grow in length, and is not intended for display purposes.
The transformations that take place under casefolding are defined by the Unicode Consortium in the CaseFolding.txt file on their website.
str.upper takes every character in a string and converts it to its uppercase equivalent, for example:
str.lower does the opposite; it takes every character in a string and converts it to its lowercase equivalent:
str.capitalize returns a capitalized version of the string, that is, it makes the first character have upper case and the rest lower:
str.title returns the title cased version of the string, that is, every letter in the beginning of a word is made upper case and all others are made lower case:
str.swapcase returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:
# Usage as str class methods
It is worth noting that these methods may be called either on string objects (as shown above) or as a class method of the str class (with an explicit call to str.upper , etc.)
This is most useful when applying one of these methods to many strings at once in say, a map
# str.translate: Translating characters in a string
Python supports a translate method on the str type which allows you to specify the translation table (used for replacements) as well as any characters which should be deleted in the process.
The translate method returns a string which is a translated copy of the original string.
You can set the table argument to None if you only need to delete characters.
# str.format and f-strings: Format values into a string
Python provides string interpolation and formatting functionality through the str.format function, introduced in version 2.6 and f-strings introduced in version 3.6.
Given the following variables:
The following statements are all equivalent
For reference, Python also supports C-style qualifiers for string formatting. The examples below are equivalent to those above, but the str.format versions are preferred due to benefits in flexibility, consistency of notation, and extensibility:
The braces uses for interpolation in str.format can also be numbered to reduce duplication when formatting strings. For example, the following are equivalent:
While the official python documentation is, as usual, thorough enough, pyformat.info
(opens new window) has a great set of examples with detailed explanations.
Additionally, the < and >characters can be escaped by using double brackets:
(opens new window) for additional information. str.format() was proposed in PEP 3101
# String module’s useful constants
Python’s string module provides constants for string related operations. To use them, import the string module:
# string.ascii_letters :
Concatenation of ascii_lowercase and ascii_uppercase :
# string.ascii_lowercase :
Contains all lower case ASCII characters:
# string.ascii_uppercase :
Contains all upper case ASCII characters:
# string.digits :
Contains all decimal digit characters:
# string.hexdigits :
Contains all hex digit characters:
# string.octaldigits :
Contains all octal digit characters:
# string.punctuation :
Contains all characters which are considered punctuation in the C locale:
# string.whitespace :
Contains all ASCII characters considered whitespace:
In script mode, print(string.whitespace) will print the actual characters, use str to get the string returned above.
# string.printable :
Contains all characters which are considered printable; a combination of string.digits , string.ascii_letters , string.punctuation , and string.whitespace .
# Split a string based on a delimiter into a list of strings
# str.split(sep=None, maxsplit=-1)
str.split takes a string and returns a list of substrings of the original string. The behavior differs depending on whether the sep argument is provided or omitted.
If sep isn’t provided, or is None , then the splitting takes place wherever there is whitespace. However, leading and trailing whitespace is ignored, and multiple consecutive whitespace characters are treated the same as a single whitespace character:
The sep parameter can be used to define a delimiter string. The original string is split where the delimiter string occurs, and the delimiter itself is discarded. Multiple consecutive delimiters are not treated the same as a single occurrence, but rather cause empty strings to be created.
The default is to split on every occurrence of the delimiter, however the maxsplit parameter limits the number of splittings that occur. The default value of -1 means no limit:
# str.rsplit(sep=None, maxsplit=-1)
str.rsplit ("right split") differs from str.split ("left split") when maxsplit is specified. The splitting starts at the end of the string rather than at the beginning:
Note: Python specifies the maximum number of splits performed, while most other programming languages specify the maximum number of substrings created. This may create confusion when porting or comparing code.
# Replace all occurrences of one substring with another substring
Python’s str type also has a method for replacing occurences of one sub-string with another sub-string in a given string. For more demanding cases, one can use re.sub
# str.replace(old, new[, count]) :
str.replace takes two arguments old and new containing the old sub-string which is to be replaced by the new sub-string. The optional argument count specifies the number of replacements to be made:
For example, in order to replace ‘foo’ with ‘spam’ in the following string, we can call str.replace with old = ‘foo’ and new = ‘spam’ :
If the given string contains multiple examples that match the old argument, all occurrences are replaced with the value supplied in new :
unless, of course, we supply a value for count . In this case count occurrences are going to get replaced:
# Testing what a string is composed of
Python’s str type also features a number of methods that can be used to evaluate the contents of a string. These are str.isalpha , str.isdigit , str.isalnum , str.isspace . Capitalization can be tested with str.isupper , str.islower and str.istitle .
str.isalpha takes no arguments and returns True if the all characters in a given string are alphabetic, for example:
As an edge case, the empty string evaluates to False when used with "".isalpha() .
# str.isupper , str.islower , str.istitle
These methods test the capitalization in a given string.
str.isupper is a method that returns True if all characters in a given string are uppercase and False otherwise.
Conversely, str.islower is a method that returns True if all characters in a given string are lowercase and False otherwise.
str.istitle returns True if the given string is title cased; that is, every word begins with an uppercase character followed by lowercase characters.
# str.isdecimal , str.isdigit , str.isnumeric
str.isdecimal returns whether the string is a sequence of decimal digits, suitable for representing a decimal number.
str.isdigit includes digits not in a form suitable for representing a decimal number, such as superscript digits.
str.isnumeric includes any number values, even if not digits, such as values outside the range 0-9.
Bytestrings ( bytes in Python 3, str in Python 2), only support isdigit , which only checks for basic ASCII digits.
As with str.isalpha , the empty string evaluates to False .
This is a combination of str.isalpha and str.isnumeric , specifically it evaluates to True if all characters in the given string are alphanumeric, that is, they consist of alphabetic or numeric characters:
Evaluates to True if the string contains only whitespace characters.
Sometimes a string looks “empty” but we don’t know whether it’s because it contains just whitespace or no character at all
To cover this case we need an additional test
But the shortest way to test if a string is empty or just contains whitespace characters is to use strip
(opens new window) (with no arguments it removes all leading and trailing whitespace characters)
# Stripping unwanted leading/trailing characters from a string
Three methods are provided that offer the ability to strip leading and trailing characters from a string: str.strip , str.rstrip and str.lstrip . All three methods have the same signature and all three return a new string object with unwanted characters removed.
str.strip acts on a given string and removes (strips) any leading or trailing characters contained in the argument chars ; if chars is not supplied or is None , all white space characters are removed by default. For example:
If chars is supplied, all characters contained in it are removed from the string, which is returned. For example:
# str.rstrip([chars]) and str.lstrip([chars])
These methods have similar semantics and arguments with str.strip() , their difference lies in the direction from which they start. str.rstrip() starts from the end of the string while str.lstrip() splits from the start of the string.
For example, using str.rstrip :
While, using str.lstrip :
# Reversing a string
A string can reversed using the built-in reversed() function, which takes a string and returns an iterator in reverse order.
reversed() can be wrapped in a call to ».join() to make a string
While using reversed() might be more readable to uninitiated Python users, using extended slicing
(opens new window) with a step of -1 is faster and more concise. Here , try to implement it as function:
# Join a list of strings into one string
A string can be used as a separator to join a list of strings together into a single string using the join() method. For example you can create a string where each element in a list is separated by a space.
The following example separates the string elements with three hyphens.
# String Contains
Python makes it extremely intuitive to check if a string contains a given substring. Just use the in operator:
Note: testing an empty string will always result in True :
# Counting number of times a substring appears in a string
One method is available for counting the number of occurrences of a sub-string in another string, str.count .
# str.count(sub[, start[, end]])
str.count returns an int indicating the number of non-overlapping occurrences of the sub-string sub in another string. The optional arguments start and end indicate the beginning and the end in which the search will take place. By default start = 0 and end = len(str) meaning the whole string will be searched:
By specifying a different value for start , end we can get a more localized search and count, for example, if start is equal to 13 the call to:
is equivalent to:
# Case insensitive string comparisons
Comparing string in a case insensitive way seems like something that’s trivial, but it’s not. This section only considers unicode strings (the default in Python 3). Note that Python 2 may have subtle weaknesses relative to Python 3 — the later’s unicode handling is much more complete.
The first thing to note it that case-removing conversions in unicode aren’t trivial. There is text for which text.lower() != text.upper().lower() , such as "ß" :
But let’s say you wanted to caselessly compare "BUSSE" and "Buße" . Heck, you probably also want to compare "BUSSE" and "BUẞE" equal — that’s the newer capital form. The recommended way is to use casefold :
Do not just use lower . If casefold is not available, doing .upper().lower() helps (but only somewhat).
Then you should consider accents. If your font renderer is good, you probably think "ê" == "ê" — but it doesn’t:
This is because they are actually
The simplest way to deal with this is unicodedata.normalize . You probably want to use NFKD normalization, but feel free to check the documentation. Then one does
To finish up, here this is expressed in functions:
# Test the starting and ending characters of a string
In order to test the beginning and ending of a given string in Python, one can use the methods str.startswith() and str.endswith() .
# str.startswith(prefix[, start[, end]])
As it’s name implies, str.startswith is used to test whether a given string starts with the given characters in prefix .
The optional arguments start and end specify the start and end points from which the testing will start and finish. In the following example, by specifying a start value of 2 our string will be searched from position 2 and afterwards:
This yields True since s == ‘i’ and s == ‘s’ .
You can also use a tuple to check if it starts with any of a set of strings
# str.endswith(prefix[, start[, end]])
str.endswith is exactly similar to str.startswith with the only difference being that it searches for ending characters and not starting characters. For example, to test if a string ends in a full stop, one could write:
as with startswith more than one characters can used as the ending sequence:
You can also use a tuple to check if it ends with any of a set of strings
# Justify strings
Python provides functions for justifying strings, enabling text padding to make aligning various strings much easier.
Below is an example of str.ljust and str.rjust :
ljust and rjust are very similar. Both have a width parameter and an optional fillchar parameter. Any string created by these functions is at least as long as the width parameter that was passed into the function. If the string is longer than width alread, it is not truncated. The fillchar argument, which defaults to the space character ‘ ‘ must be a single character, not a multicharacter string.
The ljust function pads the end of the string it is called on with the fillchar until it is width characters long. The rjust function pads the beginning of the string in a similar fashion. Therefore, the l and r in the names of these functions refer to the side that the original string, not the fillchar , is positioned in the output string.
# Conversion between str or bytes data and unicode characters
The contents of files and network messages may represent encoded characters. They often need to be converted to unicode for proper display.
In Python 2, you may need to convert str data to Unicode characters. The default ( » , "" , etc.) is an ASCII string, with any values outside of ASCII range displayed as escaped values. Unicode strings are u» (or u"" , etc.).
In Python 3 you may need to convert arrays of bytes (referred to as a ‘byte literal’) to strings of Unicode characters. The default is now a Unicode string, and bytestring literals must now be entered as b» , b"" , etc. A byte literal will return True to isinstance(some_val, byte) , assuming some_val to be a string that might be encoded as bytes.
- str.capitalize() -> str
- str.casefold() -> str [only for Python > 3.3]
- str.center(width[, fillchar]) -> str
- str.count(sub[, start[, end]]) -> int
- str.decode(encoding="utf-8"[, errors]) -> unicode [only in Python 2.x]
- str.encode(encoding="utf-8", errors="strict") -> bytes
- str.endswith(suffix[, start[, end]]) -> bool
- str.expandtabs(tabsize=8) -> str
- str.find(sub[, start[, end]]) -> int
- str.format(*args, **kwargs) -> str
- str.format_map(mapping) -> str
- str.index(sub[, start[, end]]) -> int
- str.isalnum() -> bool
- str.isalpha() -> bool
- str.isdecimal() -> bool
- str.isdigit() -> bool
- str.isidentifier() -> bool
- str.islower() -> bool
- str.isnumeric() -> bool
- str.isprintable() -> bool
- str.isspace() -> bool
- str.istitle() -> bool
- str.isupper() -> bool
- str.join(iterable) -> str
- str.ljust(width[, fillchar]) -> str
- str.lower() -> str
- str.lstrip([chars]) -> str
- static str.maketrans(x[, y[, z]])
- str.partition(sep) -> (head, sep, tail)
- str.replace(old, new[, count]) -> str
- str.rfind(sub[, start[, end]]) -> int
- str.rindex(sub[, start[, end]]) -> int
- str.rjust(width[, fillchar]) -> str
- str.rpartition(sep) -> (head, sep, tail)
- str.rsplit(sep=None, maxsplit=-1) -> list of strings
- str.rstrip([chars]) -> str
- str.split(sep=None, maxsplit=-1) -> list of strings
- str.splitlines([keepends]) -> list of strings
- str.startswith(prefix[, start[, end]]) -> book
- str.strip([chars]) -> str
- str.swapcase() -> str
- str.title() -> str
- str.translate(table) -> str
- str.upper() -> str
- str.zfill(width) -> str
String objects are immutable, meaning that they can’t be modified in place the way a list can. Because of this, methods on the built-in type str always return a new str object, which contains the result of the method call.
string — Common string operations¶
The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-dependent.
The lowercase letters ‘abcdefghijklmnopqrstuvwxyz’ . This value is not locale-dependent and will not change.
The uppercase letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’ . This value is not locale-dependent and will not change.
The string ‘0123456789’ .
The string ‘0123456789abcdefABCDEF’ .
The string ‘01234567’ .
String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`
String of ASCII characters which are considered printable. This is a combination of digits , ascii_letters , punctuation , and whitespace .
A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
Custom String Formatting¶
The built-in string class provides the ability to do complex variable substitutions and value formatting via the format() method described in PEP 3101. The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method.
class string. Formatter ¶
The Formatter class has the following public methods:
The primary API method. It takes a format string and an arbitrary set of positional and keyword arguments. It is just a wrapper that calls vformat() .
Changed in version 3.7: A format string argument is now positional-only .
This function does the actual work of formatting. It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the dictionary as individual arguments using the *args and **kwargs syntax. vformat() does the work of breaking up the format string into character data and replacement fields. It calls the various methods described below.
In addition, the Formatter defines a number of methods that are intended to be replaced by subclasses:
Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields.
The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None .
get_field ( field_name , args , kwargs ) ¶
Given field_name as returned by parse() (see above), convert it to an object to be formatted. Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101, such as “0[name]” or “label.title”. args and kwargs are as passed in to vformat() . The return value used_key has the same meaning as the key parameter to get_value() .
Retrieve a given field value. The key argument will be either an integer or a string. If it is an integer, it represents the index of the positional argument in args; if it is a string, then it represents a named argument in kwargs.
The args parameter is set to the list of positional arguments to vformat() , and the kwargs parameter is set to the dictionary of keyword arguments.
For compound field names, these functions are only called for the first component of the field name; subsequent components are handled through normal attribute and indexing operations.
So for example, the field expression ‘0.name’ would cause get_value() to be called with a key argument of 0. The name attribute will be looked up after get_value() returns by calling the built-in getattr() function.
If the index or keyword refers to an item that does not exist, then an IndexError or KeyError should be raised.
check_unused_args ( used_args , args , kwargs ) ¶
Implement checking for unused arguments if desired. The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters. check_unused_args() is assumed to raise an exception if the check fails.
format_field ( value , format_spec ) ¶
format_field() simply calls the global format() built-in. The method is provided so that subclasses can override it.
convert_field ( value , conversion ) ¶
Converts the value (returned by get_field() ) given a conversion type (as in the tuple returned by the parse() method). The default version understands ‘s’ (str), ‘r’ (repr) and ‘a’ (ascii) conversion types.
Format String Syntax¶
The str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter , subclasses can define their own format string syntax). The syntax is related to that of formatted string literals , but it is less sophisticated and, in particular, does not support arbitrary expressions.
Format strings contain “replacement fields” surrounded by curly braces <> . Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: << and >> .
The grammar for a replacement field is as follows:
In less formal terms, the replacement field can start with a field_name that specifies the object whose value is to be formatted and inserted into the output instead of the replacement field. The field_name is optionally followed by a conversion field, which is preceded by an exclamation point ‘!’ , and a format_spec, which is preceded by a colon ‘:’ . These specify a non-default format for the replacement value.
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. An arg_name is treated as a number if a call to str.isdecimal() on the string would return true. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings ’10’ or ‘:-]’ ) within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form ‘.name’ selects the named attribute using getattr() , while an expression of the form ‘[index]’ does an index lookup using __getitem__() .
Changed in version 3.1: The positional argument specifiers can be omitted for str.format() , so ‘<> <>‘.format(a, b) is equivalent to ‘ <0><1>‘.format(a, b) .
Changed in version 3.4: The positional argument specifiers can be omitted for Formatter .
Some simple format string examples:
The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__() , the normal formatting logic is bypassed.
Three conversion flags are currently supported: ‘!s’ which calls str() on the value, ‘!r’ which calls repr() and ‘!a’ which calls ascii() .
The format_spec field contains a specification of how the value should be presented, including such details as field width, alignment, padding, decimal precision and so on. Each value type can define its own “formatting mini-language” or interpretation of the format_spec.
Most built-in types support a common formatting mini-language, which is described in the next section.
A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.
See the Format examples section for some examples.
Format Specification Mini-Language¶
“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax and Formatted string literals ). They can also be passed directly to the built-in format() function. Each formattable type may define how the format specification is to be interpreted.
Most built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types.
A general convention is that an empty format specification produces the same result as if you had called str() on the value. A non-empty format specification typically modifies the result.
The general form of a standard format specifier is:
If a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (” < ” or “ >”) as the fill character in a formatted string literal or when using the str.format() method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect the format() function.
The meaning of the various alignment options is as follows:
Forces the field to be left-aligned within the available space (this is the default for most objects).
Forces the field to be right-aligned within the available space (this is the default for numbers).
Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default for numbers when ‘0’ immediately precedes the field width.
Forces the field to be centered within the available space.
Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.
The sign option is only valid for number types, and can be one of the following:
indicates that a sign should be used for both positive as well as negative numbers.
indicates that a sign should be used only for negative numbers (this is the default behavior).
indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.
The ‘z’ option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.
Changed in version 3.11: Added the ‘z’ option (see also PEP 682).
The ‘#’ option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix ‘0b’ , ‘0o’ , ‘0x’ , or ‘0X’ to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for ‘g’ and ‘G’ conversions, trailing zeros are not removed from the result.
The ‘,’ option signals the use of a comma for a thousands separator. For a locale aware separator, use the ‘n’ integer presentation type instead.
Changed in version 3.1: Added the ‘,’ option (see also PEP 378).
The ‘_’ option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type ‘d’ . For integer presentation types ‘b’ , ‘o’ , ‘x’ , and ‘X’ , underscores will be inserted every 4 digits. For other presentation types, specifying this option is an error.
Changed in version 3.6: Added the ‘_’ option (see also PEP 515).
width is a decimal integer defining the minimum total field width, including any prefixes, separators, and other formatting characters. If not specified, then the field width will be determined by the content.
When no explicit alignment is given, preceding the width field by a zero ( ‘0’ ) character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of ‘0’ with an alignment type of ‘=’ .
Changed in version 3.10: Preceding the width field by ‘0’ no longer affects the default alignment for strings.
The precision is a decimal integer indicating how many digits should be displayed after the decimal point for presentation types ‘f’ and ‘F’ , or before and after the decimal point for presentation types ‘g’ or ‘G’ . For string presentation types the field indicates the maximum field size — in other words, how many characters will be used from the field content. The precision is not allowed for integer presentation types.
Finally, the type determines how the data should be presented.
The available string presentation types are:
String format. This is the default type for strings and may be omitted.
The same as ‘s’ .
The available integer presentation types are:
Binary format. Outputs the number in base 2.
Character. Converts the integer to the corresponding unicode character before printing.
Decimal Integer. Outputs the number in base 10.
Octal format. Outputs the number in base 8.
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case ‘#’ is specified, the prefix ‘0x’ will be upper-cased to ‘0X’ as well.
Number. This is the same as ‘d’ , except that it uses the current locale setting to insert the appropriate number separator characters.
The same as ‘d’ .
In addition to the above presentation types, integers can be formatted with the floating point presentation types listed below (except ‘n’ and None ). When doing so, float() is used to convert the integer to a floating point number before formatting.
The available presentation types for float and Decimal values are:
Scientific notation. For a given precision p , formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. With no precision given, uses a precision of 6 digits after the decimal point for float , and shows all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is used.
Scientific notation. Same as ‘e’ except it uses an upper case ‘E’ as the separator character.
Fixed-point notation. For a given precision p , formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float , and uses a precision large enough to show all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is used.
Fixed-point notation. Same as ‘f’ , but converts nan to NAN and inf to INF .
General format. For a given precision p >= 1 , this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1 .
The precise rules are as follows: suppose that the result formatted with presentation type ‘e’ and precision p-1 would have exponent exp . Then, if m <= exp < p , where m is -4 for floats and -6 for Decimals , the number is formatted with presentation type ‘f’ and precision p-1-exp . Otherwise, the number is formatted with presentation type ‘e’ and precision p-1 . In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the ‘#’ option is used.
With no precision given, uses a precision of 6 significant digits for float . For Decimal , the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise.
Positive and negative infinity, positive and negative zero, and nans, are formatted as inf , -inf , 0 , -0 and nan respectively, regardless of the precision.
General format. Same as ‘g’ except switches to ‘E’ if the number gets too large. The representations of infinity and NaN are uppercased, too.
Number. This is the same as ‘g’ , except that it uses the current locale setting to insert the appropriate number separator characters.
Percentage. Multiplies the number by 100 and displays in fixed ( ‘f’ ) format, followed by a percent sign.
For float this is the same as ‘g’ , except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.
For Decimal , this is the same as either ‘g’ or ‘G’ depending on the value of context.capitals for the current decimal context.
The overall effect is to match the output of str() as altered by the other format modifiers.
This section contains examples of the str.format() syntax and comparison with the old % -formatting.
In most of the cases the syntax is similar to the old % -formatting, with the addition of the <> and with : used instead of % . For example, ‘%03.2f’ can be translated to ‘<:03.2f>‘ .
The new format syntax also supports new and different options, shown in the following examples.
3 способа обрезать строку в Python
Что вы подразумеваете под обрезкой строки и как вы можете обрезать строку в Python? Когда вы удаляете пробел вокруг струн текста, в технических условиях мы называем его обрезкой строки. В этой статье мы охватим 3 метода для обрезки строки в Python.
Техника 1: полоса (), чтобы обрезать строку в Python
Python string.strip () Функция в основном удаляет все ведущий а также Трейлистые пробелы из определенной строки. Таким образом, мы можем использовать этот метод, чтобы полностью обрезать строку в Python.
- персонаж : Это Дополнительный параметр Отказ Если передается на функцию полосы (), это удалит конкретный пропущенный символ с обоих концов строки.
В приведенном выше фрагменте кода мы прошли « @ «Как персонаж к функции полосы (), чтобы быть обрезан с обоих концов.
Метод Numpy Plass ()
Python Numpy Модуль встроен numpy.core.defcarrarray.strip () Метод, который функционирует с похожим на Python string.strip () функция.
Этот метод может быть использован для обрезки строки в Python, который встроен в массив или в любом другом ITERABLE.
Python 3: Строки. Функции и методы строк¶
Определение позиции подстроки в строке с помощью функций str.find и str.rfind .
Функция str.find показывает первое вхождение подстроки. Все позиции возвращаются относительно начало строки.
Можно определить вхождение в срезе. первое число показывает начало среза, в котором производится поиск. Второе число — конец среза. В случае отсутствия вхождения подстроки выводится -1.
Функция str.rfind осуществляет поиск с конца строки, но возвращает позицию подстроки относительно начала строки.
Python: Извлекаем имя файла из URL¶
Понадобилось мне отрезать от URL всё, что находится после последнего слэша, т.е.названия файла. URL можеть быть какой угодно. Знаю, что задачу запросто можно решить с помощью специального модуля, но я хотел избежать этого. Есть, как минимум, два способа справиться с поставленным вопросом.
Достаточно простой способ. Разбиваем строку по слэшам с помощью функции split() , которая возвращает список. А затем из этого списка извлекаем последний элемент. Он и будет названием файла.
Повторим шаг с присвоением переменной:
Второй способ интереснее. Сначала с помощью функции rfind() находим первое вхождение с конца искомой подстроки. Функция возвращает позицию подстроки относительно начала строки. А далее просто делаем срез.