In python, string is the most commonly used data type, which is usually enclosed by single quotation marks (''), double quotation marks (''), and triple quotation marks ('' ',' ').
# String creation str1 = "hello world" str2 = 'sunlight' str3 = '''On a new day, the sun rises in the East ''' str4 = """On a new day, the sun rises in the East""" str5 = "What's this?"
The strings created with single quotation marks, double quotation marks and triple quotation marks are indistinguishable. The verification is as follows
str1 = 'sunlight' str2 = "sunlight" str3 = """sunlight""" str4 = '''sunlight''' print(str1 == str2 == str3 == str4) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py True Process finished with exit code 0
The use of triple quotation marks is generally used to annotate classes and functions, or to define strings with multiple lines
A string is a sequence of independent characters, meaning that you can
1. Get string length
# Get string length str1 = 'sunlight' print(len(str1)) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py 8 Process finished with exit code 0
2. Read one of the characters by subscript
# Read characters by subscript str1 = 'sunlight' print(str1[1]) print(str1[0]) print(str1[-1]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py u s t Process finished with exit code 0
3. Read string fragments by slicing
# Read fragments in slice mode str1 = 'sunlight' print(str1[2:4]) print(str1[-4:-1]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py nl igh
4. String splicing
# String splicing str1 = 'sunlight' str2 = 'hello ' print(str2 + str1) print(str1[2:4] + str2[1:3]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py hello sunlight nlel
5. Traversal string
# Traversal string str1 = 'sunlight' for i in str1: print(i) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py s u n l i g h t Process finished with exit code 0
Escape character in python: a string that starts with a backslash to indicate a specific meaning. Common escape characters are shown in the table
# Escape example str4 = """On a new day,the sun rises in the East""" str5 = 'what\t do\b you \v do' str6 = 'What\'s this?' str7 = "It's \"cat\"" print(str4, "\n", str5, "\n", str6, "\n", str7) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py On a new day,the sun rises in the East what d you do What's this? It's "cat" Process finished with exit code 0
Common operators of strings in python
# Operator example str1 = 'sun' + 'light ' s = "r" in str1 t = "r" not in str1 w = r'\n' + R'\t' z = 3.14159 print(str1, str1*3 + "\n", s, t, "\n" + w) print("ΠThe value of is%s:" % z) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py sunlight sunlight sunlight sunlight False True \n\t ΠThe value of is 3.14159: Process finished with exit code 0
Change string:
You can directly change the value in the array by subscript, but the same operation in the string will prompt "STR 'object does not support item assignment"
# Change string str1 = 'sunlight' str1[0] = "D" print(str) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py Traceback (most recent call last): File "D:/demo/str_1.py", line 52, in <module> str1[0] = "D" TypeError: 'str' object does not support item assignment Process finished with exit code 1
Change indirectly by creating a new string
# Create a new string indirect change str1 = 'sunlight' s = "S" + str1[1:] t = str1.replace("s", "S") str1 = s print(str1, t) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py Sunlight Sunlight Process finished with exit code 0
Change by symbol + = symbol
# adopt += Symbol change str1 = 'sun' str1 += 'light' print(str1) info = "start " for s in str1: info += s print(info) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py sunlight start sunlight Process finished with exit code 0
String formatting in python
String formatting can be understood as inserting actual values into the template
# use%Implement string formatting student = {"Zhang San": 19, "Li Si": 20, "Wang Wu": 20} for info in student: print("student %s Your age is %s" % (info, student[info])) # use string.format()Method to implement string formatting prices = {"apple": 8.99, "banana": 6.99, "orange": 7.99} for price in prices: print("Fruits {}The unit price of is {}".format(price, prices[price])) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py The age of student Zhang San is 19 The age of student Li Si is 20 The age of student Wang Wu is 20 Fruits apple The unit price of is 8.99 Fruits banana The unit price of is 6.99 Fruits orange The unit price of is 7.99 Process finished with exit code 0
Common string built-in functions
string. Split (sep, maxplit): maxplit gives the value max, and the number of occurrences of sep in the string is num, and the given value is 0 < = max < = num. if sep is used as the separator to slice the string, max+1 strings will be divided. If Max is not transmitted (the default is - 1 when not transmitted) or the value passed in is greater than num, num+1 strings will be divided by default, and an array composed of strings will be returned
str1 = 'sunlight' r = str1.split("l") # maxsplit If not, the default value is-1,Return 1+1 Characters s = str1.split("l", 0) # maxsplit If 0 is passed in, 0 is returned+1 Characters t = str1.split("l", 3) # maxsplit If the incoming value is greater than the number of occurrences of the separator, 1 is returned+1 Characters w = str1.split() # sep When not transmitted, the default is blank character print(r, "\n", s, "\n", t, "\n", w) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py ['sun', 'ight'] ['sunlight'] ['sun', 'ight'] ['sunlight'] Process finished with exit code 0
string. String (chars): remove the specified chars from the beginning to the end. If it is not specified, the left and end spaces of the string will be removed by default (equivalent to the execution of string.lstrip() and string Rstrip()), and returns the stripped string
# Common built-in functions str1 = ' sunlight ' t = str1.strip() w = str1.strip("t ") print(t) print(str1) print(w) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py sunlight sunlight sunligh Process finished with exit code 0
string.rstrip(chars): remove the specified chars from the right. If it is not specified, the space at the end of the string will be removed by default, and the removed string will be returned
# Common built-in functions str1 = ' sunlight ' x = str1.rstrip() y = str1.rstrip("t ") print(str1) print(x) print(y) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py sunlight sunlight sunligh Process finished with exit code 0
string.lstrip(chars): delete the specified chars from the left. If it is not specified, the left space of the string will be removed by default, and the removed string will be returned
# Common built-in functions str1 = ' sunlight ' z = str1.lstrip() t = str1.lstrip(' su') print(z) print(t) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py sunlight nlight Process finished with exit code 0
string.find(sub, start, end): check whether the specified string sub is included in the string. If it is included, the location index value that appears for the first time will be returned. Otherwise, - 1 will be returned. Start and end are not required. If start and end are specified, search within the specified range
# Common built-in functions str1 = 'sunlightn' a = str1.find("n") # String contains n,Returns the first occurrence of the location index value 2 b = str1.find("n", 3) # The detection starts from the index of 3 and returns the location index value of 8 for the first time c = str1.find("n", 0, 2) # From index[0, 2)Start detection, no return detected-1 print(a, b, c) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py 2 8 -1 Process finished with exit code 0
string.rfind(sub, start, end): the usage is similar to find. The difference is that it returns the index value of the last position of the specified sub; otherwise, it returns - 1
# Common built-in functions str1 = 'sunlightn' e = str1.rfind("n") # String contains n,Returns the last occurrence of the location index value 8 f = str1.rfind("n", 0, 3) # From index[0, 3)Start detection print(e, f) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py 8 2 Process finished with exit code 0
string.count(sub, start, end): returns the number of times the specified sub appears in the string. If start and end are specified, statistics will be made within the specified range
# Common built-in functions str1 = ' sunlight ' j = str1.count(" ") k = str1.count(" ", 2, 9) print(j, k) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py 5 2 Process finished with exit code 0