String declaration
Double quotation marks, single quotation marks, three single quotation marks, three double quotation marks
There are double quotation marks inside and single quotation marks outside
There are single quotation marks inside and double quotation marks outside
Or use escape characters
#character string m='hello' n="hello" #There are double quotation marks inside and single quotation marks outside a='"hello"' #There are single quotation marks inside and double quotation marks outside b="I'm dq" c='''hello''' d="""hello""" i='''I say:"ok"''' j="""I'dq""" print(a,b,c,d,i,j,sep='\n')
Note: String + number cannot be used, and an error will be reported. Both must be strings
#Error TypeError: can only concatenate str (not "int") to str print("3243"+3) print("3243" + 3+"2343")
regulations:
The data of two string types uses the addition operator to splice two strings. In Python, numbers and strings cannot be added.
A multiplication operator is used between a number and a string to repeat the string multiple times.
A comparison operator is used between strings, which will be compared one by one according to the encoded value of each character.
Between numbers and strings, the result of = = operation is False, do= The result of the operation is True. Other comparison operations are not supported, otherwise an error will be reported.
Escape character
\n line feed
\t horizontal tab
\Slash
\r is enter and the cursor goes to the beginning of the line
\v: Vertical tabulation
For example:
aaaa level
a
a
a
a vertical
tab defaults to four spaces
#String 2 - escape character m='he\'ll\'o' n="he\"ll\"o" print(m,n,sep='\n')
String subscript
1. String subscript
0–n-1
-n-(-1)
2. Once the string is defined, it cannot be changed
x='89'
x[0] = '3' (error)
x = '2345' (pointing to a new string)
3. String slicing
String name [start: end: step]
step defaults to 1, taken from left to right
If only start is set, it will "intercept" to the end.
If only end is set, it will "intercept" from the beginning to the previous character of end.
All three can be defaulted, that is, all the
Forward:
#String 3 - slice 1 x='1234567' #[start:end) start from 0 - 12 print(x[0:2:1],sep='\n') #[start:end) start from 0 - 1234567 print(x[0:7:1],sep='\n') #All defaults to - 1234567 print(x[::],sep='\n') #Take out [1,3) -- 123 print(x[:3:],sep='\n') #Take every two -- 1357 print(x[0::2],sep='\n')
Reverse:
step=-1 from right to left
#String 3 - slice 2 x='1234567' #(- n) -- - 1): here - 7-- (- 1) #step=1 from left to right -- 34 print(x[-5:-3:1],sep='\n') #step=-1, from right to left, 7654 print(x[-1:-5:-1],sep='\n') #Slice every two characters from - 2 to - 5, from right to left, and output 64 print(x[-2:-5:-2]) ##Slice every 3 characters from right to left and output 741 print(x[::-3],sep='\n')
String common functions
Get string length - len() function
Find content - find() function
Description: looks up the position where the specified substring sub first appears in the string. You can specify the index and search range of the string. If none, return - 1.
Syntax: str.find (sub, start, end) - > int returns an integer
sum - substring to index.
start - the starting position of the index. The default value is 0.
End - the end position of the index. The default value is the string length len(str).
[start, end] does not include end.
#String function - find x='i love python' #Syntax: String name. Find (substring, start position, end position) #Returns the position where the character substring python first appears (subscript, starting from 0) print(x.find('python',0,len(x)),end='\n') #If not found, - 1 is returned print(x.find('python',0,6),end='\n')
Find content - rfind() function
Description: looks up the position of the last occurrence of the specified substring sub in the string. You can specify the index and search range of the string. If none, return - 1.
Syntax: str.rfind (sub, start, end) - > int returns an integer
sum - substring to index.
start - the starting position of the index. The default value is 0.
End - the end position of the index. The default value is the string length len(str).
[start, end] does not include end.
Note: the usage of rfind() function is similar to that of find() function. Rfind() function returns the last occurrence position of the specified substring, and find() function returns the first occurrence position of the specified substring.
#String function - rfind x='ip lovnep python' #Syntax: String name. Find (substring, start position, end position) #Returns the position of the last occurrence of the character substring python (subscript, starting from 0) -- n print(x.rfind('n',0,len(x)),end='\n') #Look up the first character: p--10 print(x.rfind("python")) #If not found, - 1 is returned print(x.rfind('python',0,6),end='\n')
Find content - index() function
Description: find the position of the substring that appears for the first time in the string. You can specify the index search range of the string [star, end]. If there is no, an error will be reported.
Syntax: str.index (sub, start, end) - > int returns an integer
sub -- substring to find.
start -- the starting position of the index, which is 0 by default.
End -- the end position of the index, which is the length of the string by default.
[star,end)
# String function - index str = "i love python" # Consistent with find usage print(str.index("p", 4, 12)) # If none, an error will be reported - ValueError: substring not found print(str.index("k", 4, 12)) print(str.index("i"))
Find content - rindex() function
Description: find the position of the last substring in the string. You can specify the index of the string. If there is no [star, end], an error will be reported.
Syntax: str.rindex (sub, start, end) - > int returns an integer.
sub -- substring to find.
start -- the starting position of the index, which is 0 by default.
End -- the end position of the index, which is the length of the string by default.
[star,end)
#String function - rindex str = "i love python python" #Returns the position of the next occurrence of the character substring p (subscript, starting from 0) print(str.rindex("p")) #Returns the position where the character substring o appears next (subscript, starting from 0) print(str.rindex("o",0,len(str))) # If none, an error will be reported - ValueError: substring not found print(str.rindex("x"))
Judge - endswitch() function
Description: determines whether a string ends with a specified character or substring.
Syntax: str.endswitch ("suffix", start, end) or
STR [start, end]. Endswitch ("suffix") is used to determine whether a certain string in a string ends with a specified character or substring.
- > the return value of bool is Boolean (True,False)
Suffix - suffix, which can be a single character, a string, or a tuple ("quotation marks in suffix" should be omitted).
start - the starting position of the index string.
End - the end position of the index string.
Str.endswitch (suffix) star defaults to 0, and end defaults to the length of the string minus one (len(str)-1).
Note: the case of null characters. The return value is usually True
#String function - endswitch #Find whether the string ends with a character, return True, not False str = "i love python" #True print(str.endswith("n")) #False print(str.endswith("n",0,6)) #True print(str.endswith("python")) #True print(str.endswith("python",0,len(str))) #True - empty string print(str.endswith(""))
Judge - startswitch() function
Description: determines whether a string begins with a specified character or substring.
The usage is consistent with endswitch
#String function - startswitch #Find whether the string starts with a character, return True, not False str = "ilove python" #True print(str.startswith("i")) #True print(str.startswith("i",0,6)) #True print(str.startswith("ilove")) #False print(str.startswith("python",0,len(str))) #True - empty string print(str.startswith(""))
Judge - isalpha() function
The purpose of isalpha() is to check whether all characters in a string are composed of letters and have at least one character.
string_name.isalpha()
The function has no arguments.
string_name is the string or string variable to judge.
If the string does not contain any other characters (numbers, symbols, etc.) except letters and Chinese and is not an empty string, return True; otherwise, return False
Example:
Judge - isdigit() function
The isdigit() method detects whether a string consists of only numbers.
Returns True if the string contains only numbers; otherwise, returns False.
str = "123456" #True print (str.isdigit()) str = "this is string example....wow!!!"#False print (str.isdigit()) str = "thisd22is string example....wow!!!"#False print (str.isdigit()) str = "Reliable 11"#False print (str.isdigit())
Judge - isalnum() function
Check whether a string is composed of valid characters or numbers in a language.
1) This function checks whether the string is composed of letters [a-z,A-Z] (also including characters constituting other languages, such as Chinese, Russian, Japanese, Korean) or numbers [0-9] and their combinations. If yes, it returns True, otherwise, it returns False.
3) The characters that make up the string are empty strings, no special characters, non printable characters, control characters, punctuation marks, etc. return False.
isalnum Examples of use 1,The string contains only letters str1 = "Python" print(str1.isalnum()) Output: True 2,The string contains only numbers str1 = "5211314" print(str1.isalnum()) Output: True 3,A string consists of letters or numbers str1 = "HelloPython3" print(str1.isalnum()) Output: True 4,The string consists of letters and Chinese characters rtn_value = "Xiang Yuting IT RIZ-ZOAWD".isalnum() print(rtn_value) Output: True Only Chinese characters and English letters are included, so True. 5,The string contains spaces str1 = "I am a student" print(str1.isalnum()) Output: False 6,The string contains punctuation marks str1 = "Perfect!" print(str1.isalnum()) Output: False 7,The string contains uppercase and lowercase letters str1 = "GoodBoy123" print(str1.isalnum()) Output: True 8,Null character str1 = "" print(str1.isalnum()) Output: False 9,Non English letters str1 = "Ятебялюблю" #Russian print(str1.isalnum()) Output: True 10,Contains special characters str1 = "Hello@biye5u" print(str1.isalnum()) Output: False
Judge - isspace() function
The purpose of isspace() is to check whether the string contains only white space characters (pure white space characters "", '', escape characters \ n,\t,\v,\r). If the string contains only white space characters, it returns True, otherwise it returns False.
Example 1:
Example 2:
Count - number of occurrences count() function
Description: counts the number of occurrences of a character in a string. You can select the start position and end position of the string index.
str = "i love python,i am learning python" print(str.count("i")) print(str.count("i",2)) print(str.count("i",2,5)) print(str.count("am"))
Replace content - replace() function
The replace() method replaces old (old string) in the string with new (new string). If the third parameter max is specified, the replacement shall not exceed max times.
str.replace(old, new[, max])
old – substring to be replaced.
New – a new string that replaces the old substring.
Max – an optional string that cannot be replaced more than max times
The new string generated after replacing old (old string) with new (new string) in the returned string. If the third parameter max is specified, the replacement shall not exceed max times.
example str = "this is string example....wow!!! this is really string" print (str.replace("is", "was")) print (str.replace("is", "was", 3)) Output: thwas was string example...wow!!! thwas was really string thwas was string example...wow!!! thwas is really string
Cut string - partition() function:
Description: splits a string according to the specified separator (sep). Index the separator sep from the left of the string, and stop indexing when it reaches.
Syntax: str.partition (sep) - > (head, sep, tail) returns a ternary group. Head: the string before the separator sep, sep: the separator itself, and tail: the string after the separator sep.
#String partition #The separator (sep) specified by partition('separator ') splits the string #Stop when the first delimiter is encountered #Yes: return (left of separator, right of separator) #None: return (whole string, separator) str = "https://www.baidu.com/" print(str.partition("://")) print(str.partition(",")) print(str.partition(".")) print(type(str.partition("://"))) # Output: # ('https', '://', 'www.baidu.com/') # ('https://www.baidu.com/', '', '') # ('https://www', '.', 'baidu.com/') # <class 'tuple'>
Cut string - rpartition() function
Description: splits a string according to the specified separator (sep). The index separator sep starts from the right (end) of the string, and stops when the index reaches.
Syntax: str.rpartition (sep) - > (head, sep, tail) returns a ternary group. Head: string before separator sep, sep: separator itself, tail: string after separator sep.
#String rpartition #The separator (sep) specified by rpartition('separator ') splits the string -- from right to left #Stop when the first delimiter is encountered #Yes: return (left of separator, right of separator) #None: return (separator, whole string) str = "https://www.baidu.com/" print(str.rpartition("://")) print(str.rpartition(",")) print(str.rpartition(".")) print(type(str.rpartition("://"))) # Output: # ('https', '://', 'www.baidu.com/') # ('', '', 'https://www.baidu.com/') # ('https://www.baidu', '.', 'com/') # <class 'tuple'>
Cut string - split() function
Description: splits a string. Splits the string by specifying the separator sep, and returns a list of split strings.
Syntax: str.split (SEP = none, maxplit = - 1) - > list of strings returns a list of strings or str.split (SEP = none, maxplit = - 1) [n]
sep -- separator, which is a space by default, but cannot be empty (").
Maxplit -- Maximum segmentation parameter, and the default parameter is - 1.
[n] -- returns the element with subscript n in the list. Usage of list index.
#String function - split() a="d/q.i/s.co/ding" #No segmentation, output the whole string -- ['dqiscoding '] print(a.split()) #Split by - ['dq ',' is', 'coding'] print(a.split(".")) #The first of the split string is split again, starting from 0 print(a.split('.')[0].split('/')) print(a.split('.')[1].split('/'))
Cut string - rsplit() function
The rsplit() method splits the string by specifying a separator and returns a list. The default separator is all empty characters, including spaces, line breaks (\ n), tabs (\ t), etc. it is similar to the split() method, except that it starts at the end of the string.
#String function - rsplit() #Start at the end of the string, but output from the front to the back a="d/q.i/s.co/ding" #No segmentation, output the whole string -- ['dqiscoding '] print(a.rsplit()) #Split by - ['dq ',' is', 'coding'] print(a.rsplit(".")) #1 is the maximum number of divisions. At this time, it is divided only once print(a.rsplit(".",1)) #The first of the split string is split again, starting from 0 print(a.rsplit('.')[0].rsplit('/')) print(a.rsplit('.')[1].rsplit('/'))
Cut string - splitlines() function
The splitline() method is used to split secants on line boundaries. This function returns a list of lines in a string, including line breaks (optional).
Usage:
string.splitlines([keepends])
Parameters:
Keepers (optional): when set to True, line breaks will be included in the result list.
This can be a number that specifies the position of the newline, or any Unicode character, such as "\ n", "\ r", "\ r\n" and so on, as the boundary of the string.
Code 1
string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks"
print (string.splitlines( ))
print (string.splitlines(0))
print (string.splitlines(True))
Output:
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to\r', 'the world of Geeks\n', 'GeeksforGeeks']
Code 2
string = "Cat\nBat\nSat\nMat\nXat\nEat"
print (string.splitlines( ))
print('India\nJapan\nUSA\nUK\nCanada\n'.splitlines())
Output:
['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']
['India', 'Japan', 'USA', 'UK', 'Canada']
Modify case - capitalize() function
Description: changes the first letter of a string to uppercase and the rest to lowercase.
Syntax: str.capitalize() - > STR returns a string
Program example:
str1 = "i Love python" str2 = " i Love python" str3 = "I Love python" print(str1.capitalize()) print(str2.capitalize()) print(str3.capitalize()) Program running results: I love python i love python I love python
Modify case - title() function
Description: returns a string that satisfies the title format. That is, the first letter of all English words is uppercase, and the other English letters are lowercase.
Syntax: str.title() - > STR returns a string
Program example:
str = "i love python" print(str.title()) Program running results: I Love Python
Modify case - upper() function
Description: converts all lowercase letters in a string to uppercase letters.
Syntax: str.upper() - > STR returns a string
Program example:
str1 = "i love python" str2 = "I Love Python" print(str1.upper()) print(str2.upper()) Program running results: I LOVE PYTHON I LOVE PYTHON
Modify case - lower() function
Description: converts all uppercase letters in a string to lowercase letters.
Syntax: str.lower() - > STR returns a string
Program example:
str1 = "I Love Python" str2 = "Groß - α" print(str1.lower()) print(str2.lower()) Program running results: i love python groß - α
Space handling - ljust() function
Description: returns a new string with the original string left aligned and filled with fillchar (blank by default) to the specified length. If the specified length is less than the length of the original string, the original string is returned.
Syntax: str.ljust (width, fillchar) - > STR returns a new string
width -- specifies the output length of the string.
fillchar -- the single character to be filled in. The default is space.
Program example:
str = "python" print(str.ljust(30,"*")) print(str.ljust(30)) print(str.ljust(30),"1") Program running results: python************************ python python 1
Space handling - rjust() function
Description: returns a right aligned original string and fills it with fillchar (blank by default) to a new string of the specified length. If the specified length is less than the length of the original string, the original string is returned.
Syntax: str.ljust (width, fillchar) - > STR returns a new string
width -- specifies the output length of the string.
fillchar -- the single character to be filled in. The default is space.
Program example: str = "python" print(str.rjust(30,"*")) print(str.rjust(30)) print("1",str.rjust(30)) Program running results: ************************python python 1 python
Space handling - center() function
Description: returns a string with a length of width and filled with fillchar (single character) on both sides, that is, the string str is centered and filled with fillchar on both sides. If the length of the string is greater than width, the string str is returned directly.
Syntax: str.center(width, "fillchar") - > STR returns a string. Note: quotation marks cannot be omitted
width -- specifies the length of the string.
fillchar -- the single character to be filled in. The default is space.
Program example:
str = "i love python" print(str.center(20,"*")) print(str.center(1,"*")) print(str.center(20,"8")) print(str.center(20)) Program running results: ***i love python**** i love python 888i love python8888 i love python
Space handling – strip() function
Description: removes the characters listed in chars on the left and right sides of the string str.
Note: what chars passes in is a character array. The compiler removes all corresponding characters at both ends until the first character that does not match in chars appears. Look at the example.
Syntax: str.strip (chars) - > STR returns a new string
chars -- the characters to be removed are spaces or line breaks by default.
#String function - strip str = "123456789321" #strip() removes the characters listed in chars on the left and right sides of the string str #Removed the characters containing 123 on both sides -- 456789 print(str.strip("123")) str1 = "my name is ymyyyy" #Removed the character -- name containing myis space on both sides print(str1.strip("my is")) print(str1.strip("my "))
Space handling – lstrip() function
Description: removes the characters listed in chars to the left of the string str.
#String function - lstrip #Remove the characters listed on the left until you encounter the first character that does not match in chars str1 = "bacjabck123kluabc" print(str1.lstrip("abc")) str2 = "12578asdfgh12" print(str2.lstrip("12"))
Space handling - rstrip() function
Description: removes the characters listed in chars to the right of str.
#String function - rstrip #Remove the characters listed on the right until you encounter the first character that does not match in chars str1 = "bacjabck123kluabc" print(str1.rstrip("abc")) str2 = "12578asdfgh12" print(str2.rstrip("12"))
String splicing - join() function
join(): an array of connection strings. Connect the string, tuple and elements in the list with the specified character (separator) to generate a new string
Syntax: 'sep'. join(seq)
Parameter description
sep: separator. Can be empty
seq: element sequence, string, tuple, dictionary to connect
The above syntax is to combine all the elements of seq into a new string with sep as the separator
Return value: returns a string generated after connecting the elements with the separator sep
#Operate on strings >>> seq2 = "hello good boy doiido" >>> print ':'.join(seq2) h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o