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/02 Report--
This article mainly explains the "what is the use of Python string", the content of the explanation is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "what is the use of Python string" bar!
Str (string)
1. Strings are the most commonly used data type in Python. We can define strings in four ways:'',''and''.
A = 'xperib = "y" c =' xxx'''d = "yyy" print (a recorder bpm c Magi d) # output: x y xxx yyy
two。 Strings are immutable and cannot be changed once they are defined
String = 'world'string =' hello world'
3. Escape of a string
\: line continuation;\ e: escape;\ n: line feeds;\: backslash symbols;\ ": single quotes;\": double quotes;\ 000: empty;\ v: vertical tabs;\ t: horizontal tabs;\ r: carriage returns;\ f: page feeds;\ oyy: octal numbers, characters represented by yy, for example:\ o12 represents line breaks; xyy: hexadecimal numbers, characters represented by yy, for example:\ X0a represents line feeds \ other: other characters are output in normal format
4. Strings can be accessed through index and loop iteration.
# Index access str = 'hello'print (str [1]) # output: e# Loop iterative access str1 =' hello'for item in str1: print (item) # output: hello
5. How to concatenate a string
Use the + sign to connect directly
String1 = 'hello'string2 ='\ t'string3 = 'world'print (string1 + string2 + string3) # output: hello world
Connect using the join method
Lst = ['1percent,' 2percent, '3percent,' 4percent,'5'] lst_new = '.join (lst) print (lst_new) # output: 12345
6. The cutting of strings
Use split (sep=None, maxsplit=num)-> list of strings to cut from left to right, sep specifies the delimiter, maxsplit specifies the number of cuts, and num specifies the number of cuts. If the maxsplit parameter is not set, the number of cuts is unlimited according to sep.
String1 = '1Jing 2j3j1 = string1.split (',') new_obj2 = string1.split (',', maxsplit=1) print (new_obj1) # output: ['1bike,' 2pm, '3pm,' 4pm,'5'] print (new_obj2) # output: ['1pm,' 2Ling 3pm 4pm 4J 5']
Using the rsplit method, rsplit (sep=None, maxsplit=num)-> list of strings, the parameter setting is similar to the split method, except that the rsplit method is cut from right to left
String1 = '1meme 2j3j1j1 = string1.rsplit (',') new_obj2 = string1.rsplit (',', maxsplit=1) print (new_obj1) # output: ['1pm,' 2pm, '3pm,' 4pm,'5'] print (new_obj2) # output: ['1JEI,' 2MET, 3J 4J,'5']
Use the splitlines method, splitlines ([keepends])-> list of strings, newline character ('\ r\ nmarker,\ n') cut, keepends refers to whether to retain the delimiter, True is reserved, False does not retain
String1 ='I love xkd\ nI love xkd'new_obj1 = string1.splitlines () new_obj2 = string1.splitlines (True) print (new_obj1) # output: ['I love xkd','I love xkd'] print (new_obj2) # output: ['I love xkd\ n','I love xkd']
Using the partition method, partition (sep)-> (head, sep, tail) cuts three segments from left to right, with a delimiter in the middle. If you only need to output one of the segments, you can replace the other segments with an underscore
String1 = '1meme 2, 3jue 4j1, seq, new_obj2 = string1.partition (',') print (new_obj1) # output: 1print (seq) # output:, print (new_obj2) # output: 2memoir 3Power4 newcomer obj1, _, _ = string1.partition (',') print (new_obj1) # output: 1
7. String object method
String = 'aBcd abcD' # initialize a string string
All converted to uppercase
Print (string.upper ()) # output: ABCD ABCD
All converted to lowercase
Print (string.lower ()) # output: abcd abcd
Change uppercase to lowercase, lowercase to uppercase.
Print (string.swapcase ()) # output: AbCD ABCd
Capitalize the initials of all words
Print (string.title ()) # output: Abcd Abcd
The first letter of a string is capitalized
Print (string.capitalize ()) # output: Abcd abcd
The center method, center (width [, fillchar])-> str, centers the string, width specifies the width, and fillchar specifies the filled character
Print (string.center (100,'*') output: * aBcd abcD*
The ljust method, ljust (width [, fillchar]), places the string to the left, width specifies the width, and fillchar specifies the filled character
Print (string.ljust (100,'*') output: aBcd abcD*
The rjust method, rjust (width [, fillchar]), places the string to the right, width specifies the width, and fillchar specifies the filled character
Print (string.rjust (100,'*') output: * aBcd abcD
Zfill method, zfill (width)-> str, right aligned print, left filled with 0
Print (string.zfill) output: 00000000000000000000aBcd abcD
8. String modification
Replace method, replace (old, new [, count])-> str, string substitution, old refers to the string to be replaced, new is the replacement string, and count is the specified number of times
String = 'age'print (string.replace (' averse,'z')) # output: zge
The strip method, strip ([chars])-> str, removes the characters at both ends. Chars specifies the characters to be removed, and if chars is not specified, the white space characters are removed.
String = 'age' print (string.strip ()) # output: ageprint (string.strip ()) # output: age
Lstrip: remove the characters on the left, rstrip: remove the characters on the right
Print (string.rstrip ()) # output: ageprint (string.lstrip ()) # output: age
9. String lookup
String = 'helloworld'
Find method, find (sub [, start [, end]])-> int, search from left to right, sub specifies the string to find, [start,end] returns the index for the start and end indexes
Print (string.find ('e')) # output: 1
Index method, index (sub [, start [, end]])-> int, returns the index
Print (string.index ('w')) # output: 5
Count method, count (sub [, start [, end]])-> int, returns the number of characters that appear
Print (string.count ('l')) # output: 3
10. String judgment
String = 'hello' # initialize a string string
Startswith method, startswith (prefix [, start [, end]])-> bool, whether to start with prefix
Print (string.startswith ('')) # output: True
Endswith (suffix [, start [, end]])-> bool, whether it ends with suffix
Print (string.endswith ('x')) # output: False
Whether isalnum () is a letter or a number
Print (string.isalnum ()) # output: True
Whether isalpha () is a letter
Print (string.isalpha ()) # output: True
Whether isdigit () is a number
Print (string.isdecimal ()) # output: False
Whether isdecimal () is decimal
Print (string.isdecimal ()) # output: False
Whether isidentifier () begins with a letter and an underscore
Print (string.isidentifier ()) # output: True
Whether islower () is lowercase
Print (string.islower ()) # output: True
Whether isupper () is uppercase
Print (string.isupper ()) # output: False
Whether isspace () is a full white space character
Print (string.isspace ()) # output: False
11. String formatting
C language style
Print ("I am d"% (100,)) # Front end complement 0print ('I am% s'% 'hello') # string print ('% .3f'% (99.56789)) # keep 3 decimal places print ("I am%-5d"% (20,)) # left align print ("I am% 5d"% (20,)) # align right
Python format style
S.format (* args, * * kwargs)-> str, where args is a tuple, kwargs is a dictionary, and curly braces are placeholders 1: placeholder print ('I am {}, I am in {} '.format (' fish', 'nautical mile')) print ('I am {0}, I am {1} '.format (' fish', 'nautical mile')) print ('I am {1} I am in {0} '.format (' nautical mile', 'fish',) print ('I am {1}, I am {0}'. Format (* ('nautical mile,' fish')) print ('I am {name}, I am in {addr} '.format (name=' fish', addr=' nautical mile')) print ('I am {name}) I specify 100 positions in {addr} '.format (* * {' name':' fish', 'addr':' nautical miles'}) 2: align # specify 100locations, and align print ('{0} + {1} = {2name':' 100} '.format (1d2 Magazine 3)) # specify 100locations and align to the left, and fill in 0print (' {0} + {1} = {2Flt 0100} '.format (1ZOO})) # to specify 100locations elsewhere Center align print ('{0} + {1} = {2: ^ 100} '.format (1meme 2pm 3) # specify 100 locations Center alignment, complement 0print ('{0} + {1} = {2: 0 ^ 100} '.format (1Jing 2) elsewhere ('I don't know') print ("int: {0hex d} bin: {0V b} hex: {0V x} oct: {0V o}" .format (100)) print ("int: {0V d} bin: {0V V B} hex: {0V V x} oct: {0V V O}" .format) Thank you for your reading. The above is the content of "what is the use of Python strings?" after the study of this article, I believe you have a deeper understanding of the use of Python strings, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.