search
HomeBackend DevelopmentPython TutorialIntroduction to Python basic data types

                                              python3 基本数据类型   
Python3 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。   
Python3 中有6个标准的数据类型:Number(数字);字符串(String);列表(list);元组(Tuple);字典:(Dict);集合(Sets) 
Number(数字): 
Python3支持int,float,bool,complex(复数)   
type()函数可以查看变量所指的对象类型
String(字符串):   
Python中的字符串用单引号(')或双引号(")括起来,同时使用反斜杠(\)转义特殊字符。   
注意:'''...'''三元引号在创建短字符串时没有什么特别用处,主要用于创建多行字符串,如下例:   
>>> poem =  '''There was a Young Lady of Norway,   
... Who casually sat in a doorway;   
... When the door squeezed her flat,   
... She exclaimed, "What of that?"   
... This courageous Young Lady of Norway.'''
Python也允许空串存在,不包含任何字符,完全合法!
数字与字符串之间的转换:   
字符串转换成数字:   
>>> int('20')   
20   
>>> float('20')   
20.0   
>>> int(20)   
20
数字转换成字符串:   
>>> str(20)   
'20'   
>>> str(20.0)   
'20.0'   
>>> str(True)   
'True'
使用+拼接   
在python中可以试用+将多个字符串或字符串变量进行拼接   
>>> 'Release the Tom!' + 'At once!'   
Release the Tom! At once!
使用[]提取字符   
在字符串后面添加[],在[]中添加偏移量,即可取出该位置的字符串。第一个字符偏移量为0,第二个为1,后面依次类推。   右边第一个偏移量为-1,第二个为-2,从右往左依次类推...   
>>> str = 'abcdefghijklmnopqrstuvwxyz'   
>>> str[0]   
'a'   
>>> str[-1]   
'z'   
>>> str[3]   
'd'
字符串是不可变的,有时候改变字符串,需要组合使用一些字符串函数:replace(),以及分片操作   
>>> name = 'Henny'   
>>> name.replace('H','P')    
'Penny'   
>>> 'P' + name[1:]   
'Penny'
使用[start:end:step]分片:   
分片操作:可以从一个字符串中抽取子字符串。起始偏移量start,终止偏移量end以及可选的步长step来定义一个分片   
1.[:]提取从开头到结尾的整个字符串   
2.[start:]从start提取到结尾   
3.[:end]从开头提取到end-1   
4.[start:end]从start提取到end-1结尾   
5.[start:end:step]从start提取到end-1,每个step提取一个字符
>>> str = 'qwertyuiop'   
>>> str[:]   
'qwertyuiop'   
>>> str[5:]   
'yuiop'   
>>> str[-3:]   
'iop'   
>>> str[:-3]   
'qwertyu'   
>>> str[-6:-3]   
'tyu'   
步长为3   
>>> str[::3]   
'qrup'   
利用切片反向输出字符串   
>>> str[::-1]   
'poiuytrewq'
字符串其他常用操作:   
>>> str = 'qwertyuiop' 
计算字符串的长度   
>>> len(str)   
10
使用split()分割:   
使用内置的字符串函数 split() 可以基于 分隔符 将字符串分割成由若干子串组成的 列表 。   
所谓列表(list)是由一系列值组成的序列,值与值之间由逗号隔开,整个列表被方括号所包裹。   
>>> todos = 'get gloves,get mask,give cat vitamins,call ambulance'   
>>> todos.split(',')   
['get gloves', 'get mask', 'give cat vitamins', 'call ambulance']   
上面例子中,字符串名为 todos,函数名为 split(),传入的参数为单一的分隔符split(),传入的参数为单一的分隔符 ','。   
如果不指定分隔符,那么 split() 将默认使用空白字符——换行符、空格、制表符。   
>>> todos.split()   
['get', 'gloves,get', 'mask,give', 'cat', 'vitamins,call', 'ambulance']
使用join()合并:   
可能你已经猜到了,join() 函数与 split() 函数正好相反:它将包含若干子串的列表分解,并将这些子串合成一个完整的大的字符串。join()   
>>> crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster']   
>>> crypto_string = ', '.join(crypto_list)   
>>> print('Found and signing book deals:', crypto_string) 
Found and signing book deals: Yeti, Bigfoot, Loch Ness Monster
使用replace()替换:   
>>> str = 'qwertyuiop'   
>>> str.replace('w','ooooo')   
'qoooooertyuiop'   
最多修改3处   
>>> str = 'qwerwerwerwtytewwiitw'   
>>> str.replace('w','oooo',3)   
'qooooerooooerooooerwtytewwiitw'   
计算字符串中'w'出现的次数   
>>> str.count('w')   
7

The above is the detailed content of Introduction to Python basic data types. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment