Table of Contents
Data types
Variables
Variable naming rules
Standard data types
String
String (string)
Escape characters
Modify string case
删除字符串空白
判断字符串全是字母或数字
字符串查找
字符串替换
数字(Number)
算数运算符
赋值运算符
Home Backend Development Python Tutorial Detailed explanation of Python data types: strings and numbers

Detailed explanation of Python data types: strings and numbers

Apr 27, 2022 pm 07:27 PM
python

This article brings you relevant knowledge about python, which mainly introduces issues related to data types such as strings and numbers. Let’s take a look at it together. I hope it will be helpful to everyone. .

Detailed explanation of Python data types: strings and numbers

Recommended learning: python video tutorial

Data types

Variables

Variables in Python do not need to be declared. Each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value.

In Python, a variable is a variable, it has no type. What we call "type" is the type of the object in memory pointed by the variable.

The equal sign (=) is used to assign values ​​to variables.

The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable.

message = “hello,Python"
print(message)
Copy after login

The running results are as follows:
Detailed explanation of Python data types: strings and numbers
Variables and values ​​are related one-to-one. When the program is running, one variable can only represent one value.
Python allows you to assign values ​​to multiple variables at the same time. For example:

a = b = c = 1
a, b, c = 1, 2, "runoob"
Copy after login

Variable naming rules

  1. Variable names can only contain letters, numbers and underscores. It can start with a letter or an underscore, but not a number.
  2. Variable names cannot contain spaces, but underscores can be used to separate words.
  3. You cannot use Python keywords as variable names. Python's standard library provides a keyword module that can output all keywords of the current version:
import keyword
print(keyword.kwlist)
Copy after login

Detailed explanation of Python data types: strings and numbers
Note: Use lowercase letters l and uppercase O with caution, because they may Mistaken for the numbers 1 and 0.
Generally use lowercase letters for variable names in Python. Although using uppercase letters in variable names does not cause an error, you should avoid using uppercase letters.

Standard data types

There are six standard data types in Python3:

  • Number (number)
  • String (string)
  • List(List)
  • Tuple(Tuple)
  • Set(Set)
  • Dictionary(Dictionary)

Python3 Among the six standard data types:

  • Immutable data (3): Number (number), String (string), Tuple (tuple);
  • Variable Data (3): List, Dictionary, Set.

String

String (string)

word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
Copy after login
  • Single quotes and double quotes in python Quotes are used exactly the same.
  • Use triple quotes (''' or """) to specify a multi-line string.
  • Escape character\.
  • Backslash can be used to escape Definition, use r to prevent backslashes from escaping. For example, r"this is a line with \n", then \n will be displayed, not a newline.
  • Concatenate strings literally, For example, "this " "is " "string" will be automatically converted to this is string.
  • Strings can be connected together using operators and repeated using the * operator.
  • In Python Strings have two indexing methods, starting with 0 from left to right and starting with -1 from right to left.
  • Strings in Python cannot be changed.
  • Python has no separate characters Type, one character is a string of length 1.
  • The syntax format of string interception is as follows: Variable [head subscript: tail subscript: step]
str='史迪崽儿的Python日记'
 
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第五个的字符
print(str[2:])             # 输出从第三个开始后的所有字符
print(str[1:5:2])          # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2)             # 输出字符串两次
print(str + '你好')         # 连接字符串
 
print('------------------------------')
 
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

print('\n')       # 输出空行
print(r'\n')      # 输出 \n
>>>
Copy after login

The running results are as follows:
Detailed explanation of Python data types: strings and numbers

Escape characters

  • Add tab character, "\t" to the string.
  • Add a newline character to the string, "\n".
  • Backslash symbol, "\".
  • Single quotation mark, "'".
  • Double quotes,""".
  • Press Enter, "\r".
str1 = "睡觉诗"
str2 = "\'史迪崽儿\'\t2021-12-13"
str3 = "春困秋乏夏打盹\n冬眠不是一小会"
print(str1)
print(str2)
print(str3)
Copy after login

Detailed explanation of Python data types: strings and numbers

Modify string case

  • Change the first letter of each word to uppercase, title().
  • Convert all letters to uppercase, upper().
  • Convert all letters to lowercase, lower().
str = "hello,my dear Python world"
print(str.title())
print(str.upper())
print(str.lower())
Copy after login

Detailed explanation of Python data types: strings and numbers

删除字符串空白

  • 去除末尾空白,rstrip()。
  • 去除开头空白,lstrip()。
  • 去除开头和末尾空白,strip()。
str = "   A   "
print(str)
print(str.rstrip())
print(str.lstrip())
print(str.strip())
Copy after login

如果三四看不出来区别,可点击行末尾,第三行光标停留在“A”的后面一段距离,而第四行停留在“A”后面。
Detailed explanation of Python data types: strings and numbers

判断字符串全是字母或数字

  • 判断字符串全是字母,isalpha()。
  • 判断字符串全是数字,isdigit()。
  • 判断字符串既有字母又有数字,isalnum()。
str1 = "abc"
str2 = "123"
str3 = "abc123"
print("三个字符串是否全为字母:")
print(str1.isalpha())
print(str2.isalpha())
print(str3.isalpha())
print("三个字符串是否全为数字:")
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
print("三个字符串是否既有字母又有数字:")
print(str1.isalnum())
print(str2.isalnum())
print(str3.isalnum())
Copy after login

Detailed explanation of Python data types: strings and numbers

字符串查找

  • 首词的查找,startswith()。
  • 尾词的查找,endswith()。
  • 任意位置词的查找,从左往右查find()或从右往左查rfind()。
names = "张三"
print(names.startswith("张"))
print(names.endswith("四"))
articles = "爱不是索取,亦不是占有,而是看到你幸福就好。即便这世上不再有我,即便我没法再守护你,我会化作人间的风雨,永远陪伴在你身边,永远……"
print(articles.find("守护"))
print(articles.rfind("守护"))
Copy after login

Detailed explanation of Python data types: strings and numbers
其中,38是“守护”一词的位置,从0开始计算,不管从左往右查还是从右往左查,位置不变。

字符串替换

replace(),替换。

articles = "爱不是索取,亦不是占有,而是看到你幸福就好。即便这世上不再有我,即便我没法再守护你,我会化作人间的风雨,永远陪伴在你身边,永远……"
print(articles.replace("守护","保护"))
Copy after login

Detailed explanation of Python data types: strings and numbers

数字(Number)

Python3 支持 int、float、bool、complex(复数)。

在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。

内置的 type() 函数可以用来查询变量所指的对象类型,此外还可以用 isinstance 来判断,返回bool值。

a = 111
print(isinstance(a, int))
Copy after login

isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。

**注意:**Python3 中,bool 是 int 的子类,True 和 False 可以和数字相加, True == 1、False == 0 会返回 True,但可以通过 is 来判断类型。

算数运算符

+加法
-减法
*乘法
/除法
%取余
//整除取商
**幂

赋值运算符

=赋值
+=加赋值
-+减赋值
*=乘赋值
/=除赋值
%=取余赋值
//=整除赋值
**=幂赋值

**注意:**在其他语言中,如C++,java中,都有自增自减操作符“++”,“–”,但是在Python中表示正负。

推荐学习:python视频教程

The above is the detailed content of Detailed explanation of Python data types: strings and numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles