Python learning notes Python Basics_ Data type - string

Posted by yobo on Sat, 12 Feb 2022 02:39:27 +0100

character string

String is the most commonly used data type in Python; Generally, use quotation marks' ',' ',' '(single, double and three quotation marks) and the equal sign "=" to assign a string.

str1 = 'This is a string'
str2 = "Life's short. I use python"
str3 = """
The content in the three quotation marks is also a string
 Three quotation marks are also used to indicate the description documents in the function
"""

String input

The information input by the user is received through the input() method. The default output data type of the input() method is the string type.

str4 = input('Please enter the sentence you most want to say now:') # <class 'str'>
# In this world, there are many things you want to do but haven't done, but someone has already done or completed them.
print(type(str4),{str4})
# Convert data to integer
age = int(input('How old are you this year?')) # <class 'int'>
print(f'{type(age)},You this year{age}How old are you')

String splicing

Each string can represent a paragraph or a phrase. There are two ways to splice strings.

# Method 1 uses the plus sign. Requirement: each variable or element must be of string type
agreement = 'http://'
ip = '101.02.09.33:9090'
url = '/achen/'
print(agreement + ip + url) # http://101.02.09.33:9090/achen/

# Mode 2 format output
print(f'complete URL yes:{agreement}{ip}{url}') # The full URL is: http://101.02.09.33:9090/achen/

String operation

String formatting

The so-called formatted output is to output content in a certain format
So far, as far as I know, there are three ways for python to format strings. The first is early%, followed by format() after 2.5 and f string debugging added in 3.6

Symboldescribe
%The percentage sign, the earliest format symbol, has the disadvantage that it only supports int, STR and double;
{}. Format (variable)It uses normal function call syntax (and therefore supports multiple parameters), and can__ format __ The () method extends on an object that is converted to a string. However, str.format () has the problem of code redundancy
f '{variable}'f-string is concise and easy to read. You can include the value of Python expression in the string. Include lambda expressions (in parentheses)
# This is to certify that xxx has been in the position of xxxx in xx Department of our company since xx, xx
name = "Nuo Nuo Zi"
start_year = 2017
start_month = 5
start_day = 24
department_name = 'Test management'
job = 'Test Engineer'
print('This is to certify that %s since %d year %d month %d He joined the company on September 1 and worked in our company %s department %s post' % (name,start_year,start_month,start_day,department_name,job))
print('This is to certify that {} since {} year {} month {} He joined the company on September 1 and worked in our company {} department {} post'.format(name,start_year,start_month,start_day,department_name,job))
print(f'This is to certify that {name} since {start_year} year {start_month} month {start_day} He joined the company on September 1 and worked in our company {department_name} department {job} post')

Accessing values in strings

Obtain the value of a substring in the string by intercepting the string subscript / index with square brackets. Use the variable name [index], and the index subscript starts from 0 and vice versa.

str5 = 'abcdef12345'
print(f'str5 The first character in the string is:{str5[0]}') # a
print(f'str5 The last character in the string is:{str5[-1]}') # 5

String slicing

Slicing refers to the operation of intercepting part of the operated object; String, list and tuple all support slicing
Syntax: String [start position subscript: end position subscript: step size]

  • [:] extracts the entire string from the beginning (default position 0) to the end (default position - 1)

  • [start:] extract from start to end

  • [: end] extract from the beginning to end-1

  • [start:end] extract from start to end-1

  • start 🔚 Step] extract from start to end-1, one character per step

  • [: - 1] reverse order

  • The selected interval is left closed and right open, that is, it starts from the "start" bit and ends at the previous bit of the "end" bit (excluding the end bit itself),

  • If not, the default step size is 1; The step size controls the direction. Positive numbers are taken from left to right and negative numbers are taken from right to left

str5 = 'abcdef12345'

# str5[:6] do not write before colon indicates that it starts from 0, but does not contain the position of end 5:
print(str5[:6]) # abcdef

# str5[6:] do not write after the colon, indicating from the starting position 5 to the end
print(str5[6:]) # 12345

# When there are two colons in square brackets and there is no colon before or after the first colon, it means that the beginning and beginning are the whole string, and the whole string is output
print(str5[::])  # abcdef12345
# When the interval of the second slice is: str5 followed by:]
print(str5[::2])  # ace135

# Reverse output, change the step size to a negative number
print(str5[::-1])  # 54321fedcba

String traversal

Loop through the string and output the characters one by one

str5 = 'abcdef12345'
for i in str5:
    print(i,end='\t')  # a	b	c	d	e	f	1	2	3	4	5	

Common string methods

methoddescribegrammar
find()Check whether a string is in a string. If yes, return the subscript of the starting position of the substring. Otherwise, return - 1String sequence Find (substring, start position subscript, end position subscript); The start and end subscripts can be omitted, indicating that they are found in the whole string sequence
replace()replace does not modify the original string, but generates a new stringString sequence Replace (old substring, new substring, replacement times), replace all by default; If the number of substitutions exceeds the number of occurrences of the substring, the number of substitutions is the number of occurrences of the substring
split()Separates strings by the specified characterString sequence Split (split character, num) num indicates the number of times the separator character appears. The number of data to be returned is num+1; By default, it is divided by spaces, and the split results get a list
lower()Converting a string to lowercase does not change the original string, but generates a new stringString sequence lower()
upper()Converting a string to uppercase will not change the original string, but generate a new stringString sequence upper()
strip()Delete white space characters on both sides of the stringString sequence strip()
lstrip()Delete the white space character to the left of the stringString sequence lstrip()
rstrip()Delete the white space character to the right of the stringString sequence rstrip()
startswith()Check whether the string starts with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified rangeString sequence Startswitch (substring, start position subscript, end position subscript)
endswith()Check whether the string ends with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified rangeString sequence Endswitch (substring, start position subscript, end position subscript)
isalpha()Returns True if the string has at least one character and all characters are letters; otherwise, returns FalseString sequence isalpha()
isdigit(): returns True if the string contains only numbers, otherwise FalseString sequence isdigit()
isalnum()Returns True if there is at least one character in the string and all characters are letters or numbers. Otherwise, returns FalseString sequence isalnum()
isspace()Returns True if the string contains only white space; otherwise, returns FalseString sequence isspace()
len()Statistics string lengthLen (string sequence)
str5 = 'abcdef12345abcdef'
print(f'str5 The character length of is:{len(str5)}') # 17

# find() find character
print(f'5 Where in the string:{str5.find("f",1,8)}') # 5
print(f'6 Where in the string:{str5.find("6")}') # -1. The string sequence does not contain 6
print(f'a Where in the string:{str5.find("a")}') # 0 finds the position of a in the entire string sequence 

# replace() replace character
str6 = str5.replace('abc','ABC') # Do not specify the number of times to replace all
str7 = str5.replace('abc','ABC',1) # Specify the number of times to replace the previous one first
print(str6,str7)

# split() split character
s = 'University, doctrine of the mean, Mencius, Analects of Confucius, book of songs, Shangshu, book of rites, book of changes, spring and Autumn'
print(f"Split the string with a stop sign:{s.split(',')}") # 'the book of changes', 'the book of rites',' the book of changes', 'the book of rites','
print(f'The maximum number of times to split the string into two parts:{s.split(",",4)}') # ['University', 'doctrine of the mean', 'Mencius',' Analects of Confucius', 'Book of songs, Shangshu, book of rites, book of changes, spring and Autumn']

# lower() to lowercase characters 
print(str6.lower()) # abcdef12345abcdef
# Convert upper() to uppercase characters
print(str7.upper()) # ABCDEF12345ABCDEF

# strip() delete string spaces
str8 = '  It's ah Chen '
print(f'Delete white space characters on both sides of the string:{str8.strip()}*') # Delete the blank characters on both sides of the string: ah Chen*
print(f'Delete the white space character to the left of the string:{str8.lstrip()}*') # Delete the blank character on the left side of the string: ah Chen*
print(f'Delete the white space character to the right of the string:{str8.rstrip()}*') # Delete the blank character on the right side of the string: ah Chen*

str9 = 'Chen Shenen'
filepath = 'c:/abc/dd/hhsh.doc'
# Startswitch() determines whether the string starts with xxxx - last name
print(f"Determine whether the string is xxxx start:{str9.startswith('Chen')}") # True
# Endswitch() determines whether the string ends with xxxx - file suffix
print(f"Determine whether the string is xxxx ending:{filepath.endswith('doc')}") # True

str10 = 'abcdefg'
str11 = 'abcde12345'
str12 = '1234567'
str13 = ' '
# isalpha() determines whether the string is a pure letter string
print(f'Judge whether the string is composed of pure letters:{str10.isalpha()}') # True
print(f'Judge whether the string is composed of pure letters:{str11.isalpha()}') # False

# isdigit() determines whether the string is a pure numeric string
print(f'Judge whether the string is composed of pure numbers:{str10.isdigit()}') # True
print(f'Judge whether the string is composed of pure numbers:{str12.isdigit()}') # False

# isalnum() determines whether the string contains numbers and letters
print(f'Judge whether the string is composed of numbers and letters:{str10.isalnum()}') # True
print(f'Judge whether the string is composed of numbers and letters:{str11.isalnum()}') # True
print(f'Judge whether the string is composed of numbers and letters:{str12.isalnum()}') # True

# isspace(): returns True if the string contains only white space; otherwise, returns False
print(f'Determine whether the string contains only white space:{str10.isspace()}') # False
print(f'Determine whether the string contains only white space:{str13.isspace()}') # True

Record a little every day and make progress a little every day!!!

Topics: Python