Introduction to Python quick programming # learning notes 04# | Chapter 4: string (% formatting symbol, format() formatting string, f-string formatting string and common operations of string)

Posted by liquorvicar on Wed, 13 Oct 2021 18:18:33 +0200

Leading knowledge:

Configuration and troubleshooting of development environment and Git:

Learning objectives

  • Master the definition method of string
  • Master string formatting
  • Familiar with common operation of string

4.1 string introduction

A string is a sequence of characters consisting of letters, symbols, or numbers.

String is the most common data type in Python. Quotes are generally used to create strings. Creating a string is as simple as assigning a value to a variable.

Create string example code:

# Recognize string

# String is the most common data type in Python. Quotes are generally used to create strings. Creating a string is as simple as assigning a value to a variable.
# A string is a sequence of characters consisting of letters, symbols, or numbers.
# Create string
a = 'hello world'
b = "abcdefghijkmln"
print(type(a))
print(type(b))

# Note: the console displays the output result as < class'str '> that is, the data type is str (string)

# 1.1 characteristics of string

# A pair of quoted strings

name1 = 'Tom'   # Single quotation mark
name2 = "Rose"  # Double quotation mark

# Triple quoted string

name3 = """" ROSE """
name4 = '''Tom'''
word = '''i am Tom ,
            nice to meet you!'''


print(name1)
print(name2)
print(name3)
print(name4)
print(word)

be careful:
1. The console displays the output result as < class' STR '>, that is, the data type is str (string)
2. Three quotation mark strings support line wrapping

reflection:
How do I create a string I'm Tom?

#  word2 = 'I'm Tom''    # How to write the abbreviation of I am and the prime in I'M according to the format in English grammar
#  Escape character newline: \ n; Tab: \ tis the distance of one tab (4 spaces)

 word3 = "I'm Tom"    # The first method is to use double quotation marks, and the prime 'in the middle will not appear
 word2 = 'I\'m Tom'   # The second method is to use the escape character backslash\
 print(word3)
 print(word2)
Escape character

Some ordinary characters combined with backslash will lose their original meaning and produce new meaning. Characters with special meaning, such as "\" and ", are escape characters. Transfer characters are usually used to represent characters that cannot be displayed, such as space, carriage return, etc.

Slash from top left to bottom right \ called backslash;
Slash from top right to bottom left / called slash

  • Line breaks: \ n;
  • Tab: \ tis the distance of one tab (4 spaces)

reflection:
Why does the variable output line count print() output wrap automatically?

Because the parameter end: in the print() function is used to set the output to end in writing, the default value is the newline symbol \ n.

# Output Default Wrap
print("What to output") 
print("What to output",end="\n")  # 


# If you do not want to output line breaks
 print("What to output",end=" ") 


Example code:

a = 'hello'
b = 'world!'
c = 'helloworld!'
print(a)                # String in output variable a: hello
print(b)                # String in output variable b: world!
print(c)                # String in output variable c: helloworld!
print(a, end='')        # No line break after hello output
print(b, end='\n')      # Wrap after outputting world
print('\thelloworld')   # Console output front empty 4 spaces

The output results are as follows:

4.2 format string

Format string using%

Strings have a special built-in operation that can be formatted with%.

  • Format represents a string containing one or more format characters occupying real data;
  • values represents single or multiple real data;
  • %Represents to perform formatting operations, that is, replace the format character in format with values.

Different format characters reserve space for different types of data. The common format characters are as follows:


The% formatting operation is demonstrated in PyCharm. The example code is as follows:

'''
1. Prepare data
2.Format symbol output data
'''

# 1. My age this year is x years old

# 2. My name is x

# 3. My weight is x kg

# 4. My student number is x

# Combine formatted content
# 5. My name is X. I'm x years old this year

# 6. My name is X. I'm x years old. I weigh x kilograms. My student number is X


'''**********************branch*cut*Line*********************************'''

# 1. Prepare data
age = 18
name = 'Tom'
weight = 60.5
stu_id = 1
# 2. Format symbol output data
# 1. My age this year is x -- integer% d
print("My age this year is x year")
print("My age this year is%d year" % age)

# 2. My name is x -- string% s
print('My name is TOM')
print('My name is%s' % name)

# 3. My weight is x kg -- floating point%f
print('My weight is x kg .')
print('My weight is%f' % weight)      # 6 decimal places are reserved by default
print('My weight is%.2f' % weight)    # %Add. 2 between and f and keep 2 decimal places
# Tip:%. 2f indicates the decimal places displayed after the decimal point

# 4. My student number is x
print('My student number is x')
print('My student number is%d' % stu_id)
print('My student number is%06d' % stu_id)
# Tips:%06d indicates the display digit of the output integer. If it is less than 0, it is incomplete. If it exceeds the current digit, it will be output as it is

# Combine formatted content
# 5. My name is X. I'm x years old this year
print('My name is x, this year x Years old')
print('My name is%s,this year%d Years old' % (name, age))
# 6. My name is X. I'm x years old. I weigh x kilograms. My student number is X
print('My name is x,this year x Years old, weight x Kilogram, student number is x')
print('My name is%s,this year%d Years old, weight%.2f Kilogram, student number is%d' % (name, age, weight, stu_id))

Tips:
1. %. 2f represents the decimal place displayed after the decimal point
2. % 06d indicates the display digit of the output integer. If it is less than 0, it is incomplete. If it exceeds the current digit, it will be output as it is

The output results are as follows:

Format the string using the format() method

Although% can be used to format the string, this method is not very intuitive. Once the developer misses the replacement data or selects the mismatched format character, the string formatting will fail. In order to format strings more intuitively and conveniently, Python provides a format method format() for strings.

  • str represents the string variable to be formatted. The string contains one or more symbols {} occupying real data;
  • values represents single or multiple real data to be replaced, and multiple data are separated by commas.

Method 1: the string can contain multiple {} symbols. When the string is formatted, the Python interpreter will replace {} with real data one by one from left to right by default

Examples are as follows:

name = 'Zhang Qian'
age = 25
string = "full name:{} \n Age:{}"       # Define a string, and the {} position is the placeholder of the data\ n indicates newline output
print(string.format(name, age))    # name, age are passed to the corresponding placeholder {}

The output results are as follows:

Method 2: the number can be clearly specified in {} of the string. When formatting the string, the interpreter will replace {} with the value at the corresponding position in values according to the number, and the index of the element in values starts from 0.

The example code is as follows:

name = 'Zhang Qian'
age = 25
# string = "full name:{}\n Age:{}"       # Define a string, and the {} position is the placeholder of the data
# print(string.format(name, age))    # name, age are passed to the corresponding placeholder {}

# number
string = "full name:{1}\n Age:{0}"
print(string.format(age, name))     # Numbers start at 0, 0, 1, 2, 3

Method 3: the name can be specified in {} of the string. When the string is formatted, the Python interpreter will replace the variable in {} with the name of the real data binding.

Example code:

# Specify name
name = 'Zhang Qian'
age = 25
weight = 65
string = "full name:{name} \n Age:{age} \n Weight:{weight}kg"
print(string.format(name=name, weight=weight, age=age))

Variable transfer diagram:

Recommendation: use f-string to format strings

f-string provides a more concise way to format a string. It formally leads the string with f or F, and uses "{variable name}" in the string to indicate the replaced real data and its location.

Format: F '{expression}' or F '{expression}'

Sample program:

name = 'Zhang Qian'
age = 25
print("My name is%s,My age is%d" % (name, age))
print(f'My name is{name},My age is{age}')

f '{expression}' format string is a new format method in Python 3.6. This method is simpler, easier to read and more efficient than% format string and str. format() format string. It is recommended that you use this method to format string.

4.3 training cases

slightly

4.4 common operations of string

Finding and replacing strings
find() string lookup function

Syntax format:

String sequence. Find (substring, start position subscript, end position subscript)

Note: the subscripts of the start position and the end position can be omitted, which means to find in the whole string sequence.

The example code is as follows:

my_str = "c and java and python and c++ and php"

# find()
print(my_str.find("and"))           # Find string my_ 'and' in str returns the subscript 2 of the first 'and' found
print(my_str.find("and", 5, 30))    # Find string my_ 'and' between 5 and 30 in str returns subscript 11
print(my_str.find("ands"))          # Find string my_ The "ands" in str returns the corresponding subscript if found, and - 1 if not found

Run the program, and the output results are as follows:

index() string lookup function

Syntax format:

String sequence. index (substring, start position subscript, end position subscript)

The example code is as follows:

my_str = "c and java and python and c++ and php"

# index() string lookup
print(my_str.index("and"))           # Find string my_ 'and' in str returns the subscript 2 of the first 'and' found
print(my_str.index("and", 5, 30))    # Find string my_ 'and' between 5 and 30 in str returns subscript 11
print(my_str.index("ands"))          # Find string my_ If "ands" in str is not found, an error will be reported

The output results are as follows:

count() statistics string function

Function: returns the number of times a substring appears in the string.

The example code is as follows:

my_str = "c and java and python and c++ and php"

# count() count function
print(my_str.count("and"))           # Find string my_ 'and' in str returns the subscript 2 of the first 'and' found
print(my_str.count("and", 5, 37))    # Find string my_ 'and' between 5 and 30 in str returns subscript 11
print(my_str.count("ands"))          # Find string my_ If "ands" in str is not found, an error will be reported

The output results are as follows:

  • rfind(): the same function as find(), but the search direction starts from the right
  • rindex(): the same function as index(), but the search direction starts from the right
  • count(): returns the number (count) of occurrences of a substring in the string
replace() string replacement function

Syntax: string sequence. Replace (old substring, new substring, replacement times)

Note: the replacement times can be omitted. The default is the occurrence times of all substrings in the string sequence
`

Example code:

# replace() string replacement function
# Syntax: string sequence. Replace (old substring, new substring, replacement times)
# Note: the replacement times can be omitted. The default is the occurrence times of all substrings in the string sequence

# Sample code
my_str = "c and java and python and c++ and php"
new_str1 = my_str.replace("and", "or")      # Replace string my_ All "and" in str are "or", and the new string returned by replace is assigned to new_str1
new_str2 = my_str.replace("and", "or", 1)   # Replace string my_ The first "and" in str is "or", and the new string returned by replace is assigned to new_str2
print(my_str)                               # Print out the original string 
print(new_str1)
print(new_str2)

Output results:

Summary:
1. String is an immutable data type
2. Whether data can be changed is divided into two categories: variable type (list...) and immutable type (string)

Separation and splicing of strings
split() string splitting function

Syntax: string sequence. Split ("split character", split times)

Example code:

# split() string splitting function. Returns a list, missing split characters
# Syntax: string sequence. Split ("split character", split times)
my_str = "c and java and python and c++ and php"

ls1 = my_str.split("and")
print(ls1)
ls2 = my_str.split("and", 3)
print(ls2)

Output results:

join() string merge splicing function

Example code:

Function: merge the string data in the splicing list into a large string

Syntax format: character or substring. Join (sequence composed of multiple strings)

# join() -- merge the string data in the splice list into a large string
my_list = ['aa', 'bb', 'cc', 'dd']
new_str = '+++'.join(my_list)
print(my_list)
print(new_str)

Output results:

Deletes the specified character of the string
strip() string deletion function
  • lstrip(): delete the blank character at the left of the string

  • rstrip(): deletes the white space character on the right side of the string

  • strip(): delete the blank characters on both sides of the string

Example code:

my_str = "  this is a test! "
print(my_str)

# lstrip() -- delete the left margin character
new_str1 = my_str.lstrip()
print(new_str1)

# rstrip() -- delete the right margin character
new_str2 = my_str.rstrip()
print(new_str2)

# strip()
new_str3 = my_str.strip()
print(new_str3)

Output results:

String case conversion
Capitalization() and title() string case conversion functions

Example code:

my_str = "this IS a test!"
print(my_str)

# capitalize() -- converts the first character of a string to uppercase

print(my_str.capitalize())

# title() -- converts the first letter of each word in the string to uppercase
print(my_str.title())

# lower() -- converts uppercase to lowercase in a string
print(my_str.lower())

# upper() -- converts lowercase in a string to uppercase
print(my_str.upper())

Output results:

string alignment

Syntax format: string sequence. Ljust (length, padding character)

Example code:

# just() string alignment function
# Syntax format: string sequence. [l, R, C] just (length, padding character)

my_str = " hello "
# ljust() -- align left
print(my_str.ljust(10))             # The printout is left justified "hello", and the blank space is filled with spaces

# rjust() -- align right
print(my_str.rjust(10, '_'))        # Align right with ''In the blank fill

# center() -- center alignment
print(my_str.center(10,'_'))

Output results:

Sensitive word substitution
Text typesetting tool

4.5 training cases

slightly

Focus
1. All the articles I wrote in CSDN forum are only for my own learning records, which are not comprehensive and detailed. Please forgive me! If you need detailed answers or complete learning resources (including video tutorials), welcome to my knowledge planet " Naiva's Knowledge Q & a community

2. Resources such as videos, source code, exercises and teaching courseware for getting started with Python 8G learning materials Baidu online disk download link > > click here < <, get password > > click here <<.
3. Sample code in this chapter > > click here <<

Topics: Python git Pycharm