Detailed explanation of Python data types: strings and numbers

WBOY
Release: 2022-04-27 19:27:07
forward
3079 people have browsed it

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!