In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the example analysis on the operation of Python character data. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
String operation
String + operator
The + operator is used to concatenate a string that returns a string of concatenated operands.
> s ='a'> t ='b' > > u ='c' > s + tweak ab' > s + t + upright abc' > print ('Go' +'!!') String * operator
The * operator creates multiple copies of the string. If s is a string and n is an integer, any of the following expressions returns the string s consisting of a concatenated copy of n.
> s = 'f.s * 4folf.f.f.f.4 * sfolf.f.f.f.f.`
Multiplier Operand n must be a positive integer.
>
Python also provides a member operator that can be used with strings. If the first Operand is contained in the second Operand, the in operator returns True otherwise it returns False.
> s = 'foo' > s in' That\'s food for thought.'True > s in 'That\' s good for now.'False
Used for the opposite processing operation not in operator.
>
Python provides many functions that are built into the interpreter and are always available.
Function description chr () converts integers to characters ord () converts characters to integers len () returns the length of a string str () returns the string representation of the object # ord (c) # the computer stores all information as numbers, using a conversion scheme that maps each character to its representative number # commonly known as ASCII. It covers the common Latin character that you are probably most used to using # ord (c) returns the ASCII value of character > ord ('a') 97 > ord ('#') 3percent chr (n) # chr () does the opposite of ord (), giving a value n Chr (n) returns a string # processing Unicode characters > > chr (97)'a'> chr (35)'#'> chr (8364) 'characters' > chr (8721) '∑' # len (s) # returns the length of the string. > s ='I am a string.' > len (s) 1 'str (obj) # string representation of returned objects any object in # Python can be rendered as a string > str (49.2)' 49.2'> str (3'4J)'(3'4J)'(3'4J)'> str (3 + 29)'32'> str ('foo')' foo' string index
In Python, strings are ordered sequences of character data, so they can be indexed in this way. You can access individual characters in a string by specifying a string name followed by a number in square brackets ([]).
The string index in Python is zero-based: the first character in the string has index 0, the next character has index 1, and so on. The index of the last character will be the length of the string minus 1.
> s = 'foobar'# positive index > s [0]' f'> s [1]'b' > s [3]'b' > > len (s) 6 > s [len (s)-1] 'rindexes # negative index > s [- 1]' r' > s [- 2]'a' > len (s) 6 > s [- len (s)]'f'
Attempting an index beyond the end of a string results in an error.
# positive index > s [6] Traceback (most recent call last): File ", line 1, in s [6] IndexError: string index out of range# negative index > s [- 7] Traceback (most recent call last): File", line 1, in s [- 7] IndexError: string index out of range string slice
Python also allows a form of indexed syntax called string slicing to extract substrings from strings. If s is a string, the formal expression returns the part of s [MRV n] that begins with position.
> s = 'foobar' > s [2:5]' oba'
If the first index is omitted, the slice starts at the beginning of the string. Therefore, s [: M] and s [0: M] are equivalent.
> s = 'foobar' > s [: 4]' foob' > s [0:4] 'foob'
If the second index s [n:] is omitted, the slice extends from the first index to the end of the string.
> s = 'foobar' > s [2:]' obar' > s [2: len (s)] 'obar'
For any string s and any integer n (0 ≤ n ≤ len (s)), s [: n] + s [n:] will be equal to s.
> s = 'foobar' > s [: 4] + s [4:]' foobar' > s [: 4] + s [4:] = = sTrue
Omitting two indexes returns the complete original string.
> s = 'foobar' > t = s [:] > > id (s) 59598496 > id (t) 59598496 > stride in s is tTrue string slices
For string 'foobar', slices, 0:6:2 starts at the first character, ends with the last character (the entire string), and is skipped every other character.
1:6:2 specifies a slice that starts with the second character (index 1) and ends with the last character, and the step value of 2 again causes every other character to be skipped.
> s = 'foobar' > s [0: 6:2]' foa' > s [1: 6:2] 'obr'
The first and second indexes can be omitted and default to the first and last characters, respectively.
> s = '12345' * 5 > s = '12345123451234512345123451234512345' > s [: 5] '11111' > s [4ride5]' 55555'
You can also specify a negative step value, Python will traverse the string backwards, and the start / first index should be greater than the end / second index.
> s = 'foobar' > > s [5: 0Rose Murray 2]' rbo'
The first index defaults to the end of the string and the second index defaults to the beginning.
> s = '12345' * 5 > s = '12345123451234512345123451234512345' > > s [::-5] '55555' inserts the variable into the string
F-strings provides a wide range of formatting capabilities, followed by a tutorial on formatting output.
Displays the results of the arithmetic calculation. You can do this with a simple print () statement, separating numeric values and string literals with commas.
> n = 20 > > m = 25 > > prod = n * m > print ('The product of', n,' and', m, 'is', prod) The product of 20 and 25 is 500
Using f-string recasting, the above example looks clearer.
> n = 20 > > m = 25 > > prod = n * m > print (f'The product of {n} and {m} is {prod}') The product of 20 and 25 is 500
Any of the three reference mechanisms of Python can be used to define f strings.
> var = 'Bark' > print (f'A dog says {var}!') A dog says Bark! > print (f "A dog says {var}!") A dog says Bark! > print (frankly qualified A dog says {var}!'') A dog says Bark! Modify string
String is one of the data types that Python considers immutable, and modification can lead to errors.
> s = 'foobar' > s [3] =' x'Traceback (most recent call last): File ", line 1, in s [3] = 'x'TypeError:' str' object does not support item assignment
You can easily do what you want by making a copy of the original string with the desired changes.
> s = s [: 3] +'x' + s [4:] > s = s [: 3] +'x' + s [4:] > > s = s [: 3] +'x' + s [4:] > s = s [: 3] +'x' + s [4:] > s = s [: 3] +'x' + s [4:]
You can use the built-in string method to complete the modification.
> s = 'foobar' > s = s.replace (' baked,'x') > sawfooxar 'built-in string method
Every item of data in a Python program is an object.
Dir returns a list of built-in methods and properties.
> dir ('an add__','_ class__','_ _ contains__','_ _ delattr__','_ _ dir__','_ _ doc__','_ eq__','_ format__','_ ge__','_ getattribute__','_ getitem__','_ getnewargs__','_ _ gt__' '_ _ hash__',' _ _ init__','_ _ init_subclass__','_ _ iter__','_ _ le__','_ _ len__','_ _ lt__','_ _ mod__','_ _ mul__','_ _ ne__','_ new__','_ reduce__','_ reduce_ex__','_ _ repr__' '_ _ rmod__',' _ _ rmul__','_ _ setattr__','_ _ sizeof__','_ _ str__','_ _ subclasshook__', 'capitalize',' casefold', 'center',' count', 'encode',' endswith', 'expandtabs',' find', 'format',' format_map', 'index',' isalnum', 'isalpha',' isdecimal', 'isdigit' 'isidentifier', 'islower',' isnumeric', 'isprintable',' isspace', 'istitle',' isupper', 'join',' ljust', 'lower',' lstrip', 'maketrans',' partition', 'replace',' rfind', 'rindex',' rjust', 'rpartition',' rsplit', 'rstrip',' split', 'splitlines',' startswith', 'strip',' swapcase', 'title' 'translate',' upper', 'zfill']
Method is similar to a function. A method is a special type of callable procedure that is closely associated with an object. Like a function, a method is called to perform different tasks, but it is called on a specific object and its target object is known during execution.
An example of the application of case conversion of target string
S.capitalize () capitalizes the target string
# returns a copy of the first character converted to uppercase and all other characters converted to lowercase > > s = 'foO BaR BAZ quX' > s.capitalize ()' Foo bar baz qux'# non-alphabetic characters unchanged > s = 'foo123#BAR#.' > s.capitalize ()' Foo123#bar#.'
S.lower () converts alphabetic characters to lowercase
# returns a copy of all alphabetic characters converted to lowercase > 'FOO Bar 123 baz qUX'.lower ()' foo bar 123 baz qux'
S.swapcase () swaps the case of alphabetic characters
# returns a copy of converting uppercase characters to lowercase letters, and vice versa > 'FOO Bar 123 baz qUX'.swapcase ()' foo bAR 123 BAZ Qux'
* * s.title () converts the target string to title case * *
# returns a copy of s in which the first letter of each word is converted to uppercase and the rest is lowercase > 'the sun also rises'.title ()' The Sun Also Rises'
S.upper () converts alphabetic characters to uppercase
# returns a copy of all alphabetic characters converted to uppercase > 'FOO Bar 123 baz qUX'.upper ()' FOO BAR 123 BAZ QUX'
Examples of application of search and replacement methods
S.count (, [,]) calculates the number of occurrences of substrings in the target string
# returns the number of non-overlapping occurrences in the string > 'foo goo moo'.count (' oo') 'specifies the slice location >' foo goo moo'.count ('oo', 0,8) 2
S.endswith (, [,]) determines whether the target string ends with a given substring
# s.endswith () return True if s ends with the specified end, otherwise return False > 'foobar'.endswith (' bar') True > 'foobar'.endswith (' baz') False# specify slice location > 'foobar'.endswith (' oob', 0,4) True > 'foobar'.endswith (' oob', 2,4) False
S.find (, [,]) searches the target string for a given substring
# return the index to find the substring s.find () > 'foo bar foo baz foo qux'.find (' foo')'. If the specified substring is not found, this method returns-1 > > 'foo bar foo baz foo qux'.find (' grault')-specify slice location > 'foo bar foo baz foo qux'.find (' foo', 4) 8 > 'foo bar foo baz foo qux'.find (' foo', 4,7)-1
S.index (, [,]) searches the target string for a given substring
# same as find, but no exception will be thrown > 'foo bar foo baz foo qux'.index (' grault') Traceback (most recent call last): File ", line 1, in 'foo bar foo baz foo qux'.index (' grault') ValueError: substring not found
S.rfind (, [,]) searches the target string of a given substring from the end
# return the highest index of substring found > 'foo bar foo baz foo qux'.rfind (' foo')'if no substring is found, return-1 > > 'foo bar foo baz foo qux'.rfind (' grault')-specify slice location > 'foo bar foo baz foo qux'.rfind (' foo', 0,14) 8 > > 'foo bar foo baz foo qux'.rfind (' foo', 10,14)-1
S.rindex (, [,]) searches the target string of a given substring from the end
# same as rfind, but no exception will be thrown > 'foo bar foo baz foo qux'.rindex (' grault') Traceback (most recent call last): File ", line 1, in 'foo bar foo baz foo qux'.rindex (' grault') ValueError: substring not found
S.startswith (, [,]) determines whether the target string begins with a given substring
# return the result of judging whether to start with a string > 'foobar'.startswith (' foo') True > 'foobar'.startswith (' bar') False# specify slice location > 'foobar'.startswith (' bar', 3) True > 'foobar'.startswith (' bar', 3,2) False
Examples of the application of character classification method
S.isalnum () determines whether the target string consists of alphanumeric characters
# if s is not empty and all its characters are alphanumeric (alphanumeric) return True > 'abc123'.isalnum () True >' abc$123'.isalnum () False > '.isalnum () False
S.isalpha () determines whether the target string consists of alphabetic characters
If # s is not empty and all characters are letters, return True > 'ABCabc'.isalpha () True >' abc123'.isalpha () False
S.isdigit () determines whether the target string consists of numeric characters
# return True > '123'.isdigit () True >' 123abc'.isdigit () False if it is not empty and all its characters are numbers
S.isidentifier () determines whether the target string is a valid Python identifier
# valid Python identifiers return True > 'foo32'.isidentifier () True >' 32foo'.isidentifier () False > 'foo$32'.isidentifier () False
S.islower () determines whether the alphabetic characters of the target string are lowercase
If # is not empty and all alphabetic characters it contains are lowercase, return True > 'abc'.islower () True >' abc1 $d'.islower () True > 'Abc1 $D'.islower () False
S.isprintable () determines whether the target string consists entirely of printable characters
If # is empty or all alphabetic characters contained are printable, return True >'a\ tb'.isprintable () False >'ab '.isprintable () True >' .isprintable () True >'a\ nb'.isprintable () False
S.isspace () determines whether the target string consists of white space characters
If # is not empty and all characters are blank, return True >'\ t\ n '.isspace () True >' a '.isspace () False# ASCII characters can be used as spaces >'\ f\ u2005\ r'.isspace () True
S.istitle () determines whether the target string is title case
# returns that the first alphabetic character of each word is uppercase, and all other alphabetic characters in each word are lowercase True > 'This Is A Title'.istitle () True >' This is a title'.istitle () False > 'Give Me The # $# @ Ballroomroom.istitle () True
S.isupper () determines whether the alphabetic character of the target string is uppercase
If # is not empty and all alphabetic characters it contains are uppercase, return True > 'ABC'.isupper () True >' ABC1 $D'.isupper () True > 'Abc1 $D'.isupper () False
An example of application of string format method
S.center (, []) centers the string in the field
# returns a string consisting of width-centered fields > 'foo'.center (10)' foo' # specified padding character > 'bar'.center (10,' -')'--bar----'# character length is less than the specified return character > 'foo'.center (2)' foo'
S.expandtabs (tabsize=8) expand tabs in a string
# replace each tab ('\ t') with spaces > >'a\ tb\ tc'.expandtabs ()'ab c'> 'aaa\ tbbb\ tc'.expandtabs ()' aaa bbb tab # tabsize specify alternate tab column >'a\ tb\ tc'.expandtabs (4)'ab c'> > 'aaa\ tbbb\ tc'.expandtabs (tabsize=4)' aaa bbb c'
S.ljust (, []) left align the string in the field
# returns a string consisting of left-aligned fields > 'foo'.ljust (10)' foo' # specified padding character > 'foo'.ljust (10,' -') 'foo-'# character length less than the specified original character >' foo'.ljust (2) 'foo'
S.lstrip ([]) trims leading characters in a string
# return a copy of deleting any white space characters from the left end > 'foo bar baz'.lstrip ()' foo bar baz' >'\ t\ nfoo\ t\ nbar\ t\ nbaz'.lstrip () 'foo\ t\ nbar\ t\ nbaz'
S.replace (, [,]) replaces a substring that appears in a string
# return all existing substrings replaced with copies of s.replace (,) > 'foo bar foo baz foo qux'.replace (' foo', 'grault')' grault bar grault baz grault qux'# parameter to specify the number of substitutions > 'foo bar foo baz foo qux'.replace (' foo', 'grault', 2)' grault bar grault baz foo qux'
S.rjust (, []) align the string in the field to the right
# returns a string consisting of right-aligned width fields > 'foo'.rjust (10)' foo'# specified padding character > 'foo'.rjust (10,' -')'- foo'# character length is less than the specified original character > 'foo'.rjust (2)' foo'
S.rstrip ([]) trims trailing characters in a string
# return a copy of deleting any white space characters from the right end > 'foo bar baz'. Rstrip ()' foo bar baz' > 'foo\ t\ nbar\ t\ nbaz\ t\ n'.rstrip ()' foo\ t\ nbar\ t\ nbaz'# specify the delete character set > 'foo.$$$;'.rstrip ('; $.') 'foo'
S.strip ([]) removes characters from the left and right ends of the string
# call s.lstrip () and s.rstrip () > s = 'foo bar baz\ t\ t\ t' > s = s.lstrip () > s = s.rstrip () > s'foo bar baz'# specify delete character set > 'www.realpython.com'.strip (' w.moc') 'realpython'
S.zfill () populates the string on the left with zero
# returns a copy of the left filled'0' character to the specified > '42'.zfill (5)' 00042 characters # if it contains symbols and still retains >'+ 42'.zfill (8)'+ 0000042'>'- 42'.zfill (8)'- 0000042 characters # character length is less than the specified return character >'- 42'.zfill (3)'- 42'
Application example of conversion method between iterables string and list in Sequential set
S.join () concatenates strings from iterable objects
# returns the string obtained from the separated object concatenation >, '.join ([' foo', 'bar',' baz', 'qux'])' foo, bar, baz, qux'# string operation > list ('corge') [' centering, 'oiling,' ringing,'g' The data in '.join (' corge') 'c:o:r:g:e'# list must be a string >'-- '.join ([' foo', 23, 'bar']) Traceback (most recent call last): File ", line 1, in'-- '.join ([' foo', 23, 'bar']) TypeError: sequence item 1: expected str instance, int found >'-- .join (['foo', str (23)) 'bar'])' foo---23---bar'
S.partition () divides strings based on delimiters
# the returned value is a tuple composed of three parts: front, back, > 'foo.bar'.partition ('.') ('foo',', 'bar') >' foo@@bar@@baz'.partition ('@ @') ('foo',' @ @', 'bar@@baz') # if not found, 2 empty characters are returned >' foo.bar'.partition ('@ @') ('foo.bar',') '')
S.rpartition () divides strings based on delimiters
# same as s.partition (), used to specify the last splitter > 'foo@@bar@@baz'.partition (' @ @') ('foo',' @ @', 'bar@@baz') >' foo@@bar@@baz'.rpartition ('@ @') ('foo@@bar',' @ @', 'baz')
S.rsplit (sep=None, maxsplit=-1) splits a string into a list of substrings
# returns a substring separated by any sequence of spaces And use the substring as a list > 'foo bar baz qux'.rsplit () [' foo', 'bar',' baz', 'qux'] >' foo\ n\ tbar baz\ r\ fqux'.rsplit () ['foo',' bar', 'baz',' qux'] # specify the splitter > 'foo.bar.baz.qux'.rsplit (sep='.') [' foo', 'bar',' baz' 'qux'] # specify maximum number of splits >' www.realpython.com'.rsplit (sep='.', maxsplit=1) ['www.realpython',' com'] > 'www.realpython.com'.rsplit (sep='.', maxsplit=-1) [' www', 'realpython',' com'] > 'www.realpython.com'.rsplit (sep='.') [' www', 'realpython',' com']
S.split (sep=None, maxsplit=-1) splits a string into a list of substrings
# as with s.rsplit (), the split is calculated from the left end instead of the right side > > 'www.realpython.com'.split ('.', maxsplit=1) ['www',' realpython.com'] > 'www.realpython.com'.rsplit (', maxsplit=1) ['www.realpython',' com']
S.splitlines ([]) breaks the string at the line boundary
# returns the list of newline syncopation It contains\ n,\ r,\ r\ n,\ v or\ x0b,\ f or\ x0c,\ x1c,\ x1d,\ x1e,\ x85,\ u2028,\ u2029 > 'foo\ nbar\ r\ nbaz\ fqux\ u2028quux'.splitlines () [' foo', 'bar',' baz', 'qux',' quux'] # multiple blank lines exist at the same time > > 'foo\ f\ f\ fbar'.splitlines () [' foo',','' 'bar'] # can also retain the line boundary symbol >' foo\ nbar\ nbaz\ nqux'.splitlines (True) ['foo\ n', 'bar\ n', 'baz\ n', 'qux'] >' foo\ nbar\ nbaz\ nqux'.splitlines (1) ['foo\ n', 'bar\ n', 'baz\ n', 'qux'] bytes object
Object is one of the core built-in types of bytes that manipulate binary data. The bytes object is an immutable sequence of single byte values.
Define a literal bytes object
The bytes definition of the text is the same as the string text that is prefixed with'b'.
> b = b'foo bar baz' > bb'foo bar baz' > type (b)
You can use any single, double, or triple quotation mark mechanism.
> > b'Contains embedded "double" quotes'b'Contains embedded "double" quotes' > > b "Contains embedded 'single' quotes" b "Contains embedded' single' quotes" > b'''Contains embedded "double" and 'single' quotes'''b'Contains embedded "double" and\' single\ 'quotes' > > b "" Contains embedded "double" and' single' quotes "" b'Contains embedded "double" and\ 'single\' quotes'
The'r 'prefix can be used on text to disable bytes processing of escape sequences.
> b = rb'foo\ xddbar' > > bb'foo\\ xddbar' > > b [3] 92 > chr (92)'\ 'bytes uses the built-in bytes () function to define the object
The bytes () function also creates a bytes object. Which bytes object is returned depends on the parameters passed to the function.
Bytes (,) bytes creates an object from a string
# convert strings to bytes objects according to the specified usage > b = bytes ('foo.bar',' utf8') > bb'foo.bar' > type (b)
Bytes () creates an bytes object consisting of null (0x00) bytes
# defines that the object specified by bytes must be a positive integer. > b = bytes (8) > bb'\ X00\ x00\ x00 > type (b)
Bytes () bytes creates an object from an iterable object
# defines an object n 0 ≤ n ≤ 255 > b = bytes ([100,102,104,106,108]) > bb'dfhjl' > type (b) > b [2] 104bytes object operation, operation reference string.
Operators in and not in
> b = baked abcde'> > baked cd' in bTrue > baked foo' not in bTrue
* concatenation (+) and copy () operators
> b = baked abcde' > > b + breadfghibaked abcdefghi` > b * 3broomabcdeabcdeabcde`
Index and slicing
> b = baked abcde' > b [2] 99 > b [1:3] baked bc'
Built-in function
> > b = len (b) 23 > > min (b) 44 > max (b) 122 > > b = bazefooforme > > b.count (baked foo') 3 > b.endswith (bounqux`) True > b.find (baked baz') 12 > b.split (sep=b',') [baked fooballs, baked foodies, baked foodies] > > b.center (30) List (b) [102,111,111,44,98,114,44,102,111,111,44,97,122,102,111,111,111,44,113,117,120]
Bytes.fromhex () returns an object constructed by bytes from a string of hexadecimal values
# return bytes object that converts each pair of hexadecimal digits into corresponding byte values > b = bytes.fromhex ('aa 68 4682cc') > bb'\ xaahF\ x82\ xcc' > list (b) [170,104,70,130,204]
B.hex () bytes returns a string of hexadecimal values from the object
# the result of converting bytes object b to a hexadecimal digit pair string is opposite to .fromhex () > > b = bytes.fromhex ('aa684682cc') > bb'\ xaahF\ x82\ xcc' > b.hex ()' aa684682cc' > type (b.hex ()) bytearray object, another binary sequence type supported by Python
Bytearray always uses built-in functions to create an object bytearray ()
> ba = bytearray ('foo.bar.baz',' UTF-8') > babytearray (breadfoo.bar.baz') > > bytearray (6) bytearray (b'\ X00\ x00\ x00') > > bytearray ([100102104106108]) bytearray (bicondfhjl')
The bytearray object is mutable, and the contents of the object can be modified using indexes and slices
> ba = bytearray ('foo.bar.baz',' UTF-8') > babytearray (breadfoo.bar.baz') > ba [5] = 0xee > babytearray (b'foo.b\ xeer.baz') > ba [8:11] = bamboqux'> babytearray (b'foo.b\ xeer.qux')
Bytearray objects can also construct bytes directly from objects.
> ba = bytearray (breadfoo') > babytearray (breadfoo') on the "Python character data operation example analysis" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.