In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the knowledge points of Python string". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
String creation
Use single or double quotation marks.
The str method, str (not a string parameter), converts other types to strings.
Escape character
\ n: newline character, the beginning of a new line.
\ r: carriage return, move to the beginning of the line.
\ t: horizontal tab, the beginning of the next set of 4 spaces.
\ b: backspace character, back one character.
\': single quotation marks.
\ ": double quotation marks.
Special string
The string is preceded by r, which means that the escape character does not take effect, but it cannot end with the singular\, it can end with\.
The string is preceded by u, which indicates that it is encoded in Unicode format, which is generally used in front of the Chinese string to prevent garbled code.
The string is preceded by b, indicating that this is a bytes object, which can be understood as a binary byte string, which is a special string.
Characters that span multiple lines
Three quotes (can be nested.
Add\ at the end of each line.
String addition, multiplication
Addition concatenates two strings to generate a new string.
Multiplication repeats the string n times to generate a new string.
String lookup operation
Find the element through the index, the same as the list: specify the index to get the element, and slice to get the element.
Getting the index of the substring means finding the substring in the string and returning the index of the first character that matches.
Methods index, find, rindex, rfind:
When there are multiple substrings in a string:
Index and find return the index of the first substring.
Rindex,rfind returns the index of the last substring.
When there is no substring in the string:
Index,rindex returns ValueError.
Find,rfind returns-1.
String is an immutable type with no additions, deletions or modifications
The essence of adding, deleting and modifying a string is to create a new string.
Comparison of strings
The comparison of a string compares the size of its ASCII value.
Ord (), the argument is a character (which can be Chinese) and returns its ASCII value (int).
Chr (), the argument is a number (int), and returns the corresponding character.
= = is not different from is in the string; = is different from is in the list.
String inversion and interception
Obtained by slicing, for example:
A='abc'b=a [::-1] # string reversal c = a [1:3] # string interception, subscript starting from 0, remember that left open and right close print (a dyadic) out:abc cba bc uses% as a placeholder to format the string
The string'% actual value 'containing the% placeholder contains the string'%% (actual value 1, actual value 2...) .
When% in a formatted string is a normal character, it needs to be escaped to%.
The placeholder% can be followed by a width and precision for example:% 6.3f represents a floating-point number with a width of 6 precision 3.
Format a string using {} as a placeholder
Case study:
Num=3.1415926print (f'{num:.4f}') # take 3 places after the decimal point, note that it is rounded out:3.1416
You can use colons in {} to specify the representation of numbers.
{: d} decimal number.
{: B} binary number.
{: X} hexadecimal number, lowercase.
{: X} hexadecimal number, expressed in uppercase.
{: F} floating point number.
{: .2f} take 2 places after the decimal point and round it up.
{:,} thousand-bit delimiter.
Width and precision can be specified in {}.
The representation of the {: m.n} number.
Case conversion of string
Convert case:
S.upper () is all converted to uppercase.
S.lower () is all converted to lowercase.
S.swapcase () changes all lowercase to uppercase and all uppercase to lowercase.
The first letter of the s.capitalize () string is capitalized.
All the first letters of s.title () are capitalized.
Determine whether or not case:
S.isupper () determines whether it is all uppercase.
S.islower () determines whether it is all lowercase.
S.istitle () determines whether all characters are capitalized.
Alignment of strings
Method center,ljust,rjust:
No padding character is specified, default is a space; if the specified width is less than the length of the string, the string itself is returned.
S.center (string width, padding character).
S.ljust (string width, padding character).
S.rjust (string width, padding character).
Method zfill:
S.zfill (string width) is aligned to the right and filled with 0 on the left.
Substring substitution of string, method replace
S.replace (matching string, target string, maximum number of replacements), and the maximum number of replacements can also be unspecified, indicating that there is no limit.
Character conversion of string
Methods maketrans and translate can be understood as codebook encoding and decoding.
First create an encryption dictionary trantab with maketrans.
Then s.translate (trantab) can be converted into ciphertext.
You can make a decryption dictionary and turn it back to plaintext.
Str1 = "this is string example wow!" intab = "aoeiu" # the original character and the target character correspond to outtab = "12345" # turn a to 1, o to 2, etc. Trantab = str1.maketrans (intab, outtab) # encryption dictionary trantab2 = str1.maketrans (outtab, intab) # decryption dictionary str2 = str1.translate (trantab) str3 = str2.translate (trantab2) print (str2) print (str3) out:th5s 4s str4ng 3x1mpl3 w2wregions this is string example wow!
You can also use the third parameter to specify the string to be deleted:
Str1 = "thisisstringexamplewow!" intab = "aoeiu" # the original character and the target character correspond to outtab = "12345" # to turn a to 1, o to 2, etc. Trantab = str1.maketrans (intab, outtab,'') trantab2 = str1.maketrans (outtab, intab) str2 = str1.translate (trantab) str3 = str2.translate (trantab2) print (str2) print (str3) 5s4sstr4ng3x1mpl3w2wroomthisisstringexampleexamples! Splitting of strings
S.split () looks from left to right, splits the string according to the splitter, and puts it in the list.
S.rsplit () looks from right to left, splits the string according to the splitter, and puts it in the list.
Both of the above two methods have parameters: (number of maxsplit=, sep=' splitter'):
Number of maxsplit= splits, sep=' splitter'.
S.splitlines () splits the string according to the newline character\ nand puts it into the list:
Partition (sep=' splitter'), rpartition (sep=' splitter'), splits the string into three parts. Before the splitter, after the splitter, and then encapsulate the three parts into tuples as the method returns the value.
S.partition ('splitter') looks for the splitter from the left, where it first appears.
S.rpartition ('splitter') looks for the splitter from the right, where it first appears.
If the specified splitter does not exist in the string:
The three parts of the string in the tuple returned by rpartition are: the string itself, the empty string, and the empty string.
The three parts of the string in the tuple returned by rpartition are: empty string, empty string, and string itself.
Merging of strings
One is to merge with +:
The advantage is that the code is concise, and the disadvantage is inefficiency (a new string is created for each merge).
The second is to use join () method:
Tuples, lists, and dictionaries (key) can be converted into strings, but their elements must all be strings, and non-strings will report errors. Examples are as follows:
List= ['abb',' bcc', 'cdd'] print ('. Join (list)) # abbbcccddout:abbbcccdd
It is recommended to use join () when merging a large number of strings in the body of the loop, which is more than 10 times faster than using + directly.
Import timedef strplus (): T1 = time.time () str1 =''for i in range (1000000): str1 + =' Chinese'T2 = time.time () return T2-t1def strjoin (): T1 = time.time () list1 = [] for i in range (1000000): list1.append ('Chinese') str2 = '.join (list1) T2 = time.time () return T2-t1print (strplus ()) # 1.0035312175750732print (strjoin ()) # 0.08500289916992188out:1.00353121757507320.08500289916992188 string method starting with is
S.isidentifier (): determines whether the string is a legal identifier.
S.isspace (): determines whether the string consists entirely of spaces.
S.isdecimal (): determines whether the string consists entirely of decimal numbers.
S.isnumeric (): determines whether the string consists entirely of numbers.
S.isalnum (): determines whether a string consists only of numbers and letters.
S.isalpha (): determines whether the string is made up of all letters.
Methods of removing string blank characters: strip, lstrip, rstri.ps
The strip ([chars]) default parameter removes the leading and trailing blank characters (\ n,\ t,\ r, space), and removes the specified character when you specify the parameter.
The space character (\ n,\ t,\ r, space) at the beginning of the s.ltrip ([chars]) default parameter is removed, and the specified character is removed when the parameter is specified.
Remove the trailing space (\ n,\ t,\ r, space) when s.rtrip ([chars]) is the default parameter, and remove the specified character when you specify the parameter.
This is the end of the content of "what are the knowledge points of Python string". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.