[Deep Learning] Python and NumPy Series Tutorials (2): Python Basic Data Types: 3. Strings (Indexing, Slicing, Operations, Formatting)

Table of contents

I. Introduction

2. Experimental environment

Three, Python basic data types

3. Strings

1. Initialization

2. Index

3. Slice

4. Operation

a. Splicing operation

b. Copy operation

c. Substring judgment

d. Take the length

5. Formatting

a. Use positional parameters

b. Use keyword arguments

c. Use attribute access

f-string method


I. Introduction

        Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.

        Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:

  • Python: basic data types, containers (lists, dictionaries, sets, tuples), functions, classes
  • Numpy: arrays, array indexing, data types, array math, broadcasting
  • Matplotlib: plots, subplots, images
  • IPython: Creating notebooks, typical workflow

2. Experimental environment

        Python 3.7

        Run the following command to check the Python version

 python --version 

Three, Python basic data types

Python's basic data types include:

  1. Integer (int): represents an integer value, such as 1, 2, -3, etc.
  2. Float: represents a value with a decimal point, such as 3.14, 2.5, etc.
  3. Boolean: A logical value representing True or False.
  4. String (str): Represents text data, enclosed in quotation marks (single quotation marks or double quotation marks), such as "Hello", 'Python', etc.
  5. List (list): Represents a set of ordered elements that can contain different types of data, enclosed in square brackets, such as [1, 2, 3], ['apple', 'banana', 'orange'], etc.
  6. Tuple: similar to a list, but not modifiable, enclosed in parentheses, such as (1, 2, 3), ('apple', 'banana', 'orange'), etc.
  7. Set (set): Indicates a set of unique elements enclosed in braces, such as {1, 2, 3}, {'apple', 'banana', 'orange'}, etc.
  8. Dictionary (dict): Indicates the mapping relationship of key-value pairs, enclosed in braces, such as {'name': 'John', 'age': 25}, etc.

3. Strings

        Strings are another basic data type in Python, used to represent text data. A string consists of a sequence of characters and can be enclosed in single or double quotes. For example: "Hello World" is a string.

        Strings can be manipulated in a variety of ways, such as concatenation (via the plus operator), slicing (via the indexing and slicing operators), length calculations (via the len() function), and more. You can also use various string methods to manipulate and convert strings.

        Strings are immutable in Python, which means that once a string object is created, its value cannot be modified. But new string objects can be created through string methods and operations.

        String is a very commonly used data type in Python, used to process text data, represent file paths, store user input, etc. They provide rich functions and operations, making processing text data convenient and efficient.

1. Initialization

        Strings can be initialized using single or double quotes.

str1 = 'Hello World'
str2 = "Python is awesome"

2. Index

        You can use indexing operators (square brackets) to access individual characters in a string. The indexes of strings start at 0, with the leftmost character having index 0, and increasing in sequence. For example, you can get the characters in a string using:

str1 = 'Hello World'
print(str1[0])  # 输出:H
print(str1[6])  # 输出:W

3. Slice

  • Pattern: <string> [begin: end: step]
    • ­ Close left and open right : Taking step as the step size, take all elements from begin to end-1
    • ­ The positive and negative of the step represents the direction : when the step is negative, the output needs to be reversed
    • ­ Default value : begin=0 ; end= len (<string> ) ; step =1

        You can use the slicing operator (colon) to get substrings of a string. A slice operation can specify a start index and an end index, where the start index is included in the slice and the end index is not. For example, you can get a substring of a string using:

str1 = 'Hello World'
print(str1[0:5])      # 输出:Hello
print(str1[6:])       # 输出:World
print(str1[0:10:2])   # 输出:HloWr

4. Operation

a. Splicing operation

        Two strings can be concatenated using the plus operator (+).

str1 = 'Hello'
str2 = 'World'
result = str1 + ' ' + str2
print(result)  # 输出:Hello World

b. Copy operation

        You can use the multiplication operator (*) to copy a string multiple times.

str1 = 'Hello'
result = str1 * 3
print(result)  # 输出:HelloHelloHello

c. Substring judgment

        You can use the inAND not inoperator to determine whether a string is a substring of another string. For example:

str1 = 'Hello World'
print('Hello' in str1)  # 输出:True,'Hello'是'Hello World'的子串
print('abc' not in str1)  # 输出:True,'abc'不是'Hello World'的子串

d. Take the length

        You can use len()the function to get the length of a string, that is, the number of characters in the string. For example:

str1 = 'Hello World'
length = len(str1)
print(length)  # 输出:11

5. Formatting

format()The value of a variable can be inserted into a string         using the string methods. Placeholders (curly braces) can be used to specify where variables are inserted. For example:

name = 'Alice'
age = 25
message = 'My name is {} and I am {} years old.'.format(name, age)
print(message)  # 输出:My name is Alice and I am 25 years old.

        String formatting can be achieved using slot format control. A slot is a placeholder that specifies the position in the format string where the variable value should be inserted. In the slot, you can use indexes, keyword parameters, and attribute access to control the formatting method.

        The following are several common slot format control methods:

a. Use positional parameters

        An index can be used to specify the position of the variable to be inserted.

name = 'Alice'
age = 25
message = 'My name is {0} and I am {1} years old.'.format(name, age)
print(message)  # 输出:My name is Alice and I am 25 years old.

b. Use keyword arguments

        Variables to insert can be specified using variable names as keyword arguments.

name = 'Alice'
age = 25
message = 'My name is {name} and I am {age} years old.'.format(name=name, age=age)
print(message)  # 输出:My name is Alice and I am 25 years old.

c. Use attribute access

        If the variable you want to format is a property of an object, you can use the dot (.) to access the property. For example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person('Alice', 25)
message = 'My name is {p.name} and I am {p.age} years old.'.format(p=person)
print(message)  # 输出:My name is Alice and I am 25 years old.

f-string method

        Additionally, more advanced formatting methods such as f-string can be used. f-string is a string formatting method introduced in Python 3.6 and higher, which is more concise and convenient to use.

name = 'Alice'
age = 25
message = f'My name is {name} and I am {age} years old.'
print(message)  # 输出:My name is Alice and I am 25 years old.

  

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/132765915