004、python 运算符 和 字符串操作

 

本节内容:

一、python运算符: 算术、赋值、比较运算符、逻辑运算符。

二、python 字符串操作:

  a、索引取值、切片

  b、拼接、转义

  c、常见操作

  d、格式化输出

 

 

1a、算术运算   +     —     *      /     %

   示例代码如下: 

a = -15
b = 2
c = 3.1415
d = -7

# 算术运算——加法
print(a + b)
print(a + c)

# 算术运算——减法
print(a - b)

# 算术运算——乘法
print(a * b)

# 算术运算——除法
print(a / b)
print(d//b)     # 地板除,取小于结果的整数,比如:-7.5 , 输出-8
print(round(3.14159))       # 四舍五入
print(round(3.54159))

# 算术运算——取模运算
print(a % b)
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/demo_3.py
-13
-11.8585
-17
-30
-7.5
-4
3
4
1

Process finished with exit code 0
View Code

 

1b、赋值运算:   =      +=      -=     *=    %=

# -*- coding:utf-8 -*-
# @Author:  Sky
# @Email:   2780619724@qq.com
# @Time:    2021/7/22 21:56


# a = 15
# b = 2
# c = 3.1415
#
# # 算术运算——加法
# print(a + b)
# print(a + c)
#
# # 算术运算——减法
# print(a - b)
#
# # 算术运算——乘法
# print(a * b)
#
# # 算术运算——除法
# print(a / b)
#
# # 算术运算——取模运算
# print(a % b)


a = 15
b = 2
c = 3.1415

# = 赋值运算
d = 15 % 2
print(d)

# += 累加赋值
b += a
print(b)

# -= 累减赋值
a -= b
print(a)

# *= 累乘赋值
c *= b
print(c)


e = 7
f = 2

e %= f
print(e)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py
1
17
-2
53.4055
1

Process finished with exit code 0
View Code

 

 1c、比较运算符     ==   、 !=、  > 、 >=  、 < 、 <=

#  比较运算符     ==   、 !=、  > 、 >=  、 < 、 <=
a = 3
b = 4
c = 'hello'
d = 'world'

print(a == b)
print(c == d)
print(b == c)

print(a != b)
print(a > b)
print(a >= b)
print(a < b)
print(a <= b)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py
False
False
False
True
False
False
True
True

Process finished with exit code 0
View Code

 

不同数据类型可以 == 比较, >  或  < 比较 报错 。 可以比较人与狗是否相等,但是 人 跟  动物 没有必要比较大小、优劣 ;

a = 12
b = 'hello'

print(type(a))
print(type(b))

c = (a == b)
d = (a > b)
print(c)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py
<class 'int'>
<class 'str'>
Traceback (most recent call last):
  File "D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py", line 89, in <module>
    d = (a > b)
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1
View Code

 

 1d、逻辑运算符   and(与) 、 or(或)、  not(非)

    如果有not先运算not,然后其他的 ;

  示例代码如下:

#  and(与) 、 or(或)、  not(非)
a = True
b = False

print(a and b)
print(a or b)
print(not a)

# 输出False表示:not (1 > 2 or 1 == 1)
# 输出True表示:(not 1 > 2) or 1 == 1
print(not 1 > 2 or 1 == 1)
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/demo_3.py
False
True
False
True

Process finished with exit code 0
View Code

 

 

2a、字符串切片

   字符串切片,[1:3]  包头不包尾  [1:3)

   print(var1[::-1])       # 反转  

  示例代码如下:

var1 = 'Hello World!'
var2 = "Runoob"

#  索引值以 0 为开始值,-1 为从末尾的开始位置。
print(var1[:3])
print(var1[0:3])

print(var1[1:])
print(var1[1:20])

print(var1[1::2])       # 截取步长
print(var1[::-1])       # 反转
print(var1[:])          # 获取所有

print(var1[-1])         # 取最后一个字符


print('====================')
var3 = 'abcdefghijk'
print(var3[-6:-1:1])
print(var3[-1:-6:-1])
print(var3[1:6:1])
print(var3[6:1:-1])
# 索引起点 + 步长(正数或负数)  能到达索引终点,表达式可以运算;
print('====================')
print(var3[-6:-1:-1])       # 输出空
print(var3[1:6:-1])         # 输出空
print('====================')
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/demo_3.py
Hel
Hel
ello World!
ello World!
el ol!
!dlroW olleH
Hello World!
!
====================
fghij
kjihg
bcdef
gfedc
====================


====================

Process finished with exit code 0
View Code

 

2b、字符串常见操作

  全部大写:  upper()

  全部小写:  lower()

  查找:   find(子字符串)   返回匹配到的第一个索引 ,未查到返回  -1

  index():    未查到会报错, 与 find()  不一样 

  替换:   replace(旧,新,[替换的次数])

   

var1 = 'Hello World!'
var2 = 'Hello World! Hello World! Hello World!'

print(var1.upper())
print(var2.lower())

print(var1.find('w'))
print(var1.find('W'))

print(var2.replace('World', 'java', 2))     # 替换2个

print(var1.index('W'))
# print(var1.index('w'))  #  报错 ValueError: substring not found
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py
HELLO WORLD!
hello world! hello world! hello world!
-1
6
Hello java! Hello java! Hello World!
6

Process finished with exit code 0
View Code

 

 

3a、格式化输出

print('我的名字是:{},我来自{}'.format('sky', '湖南'))
print('我的名字是:{0},我来自{1}'.format('sky', '湖南'))

print('我的名字是:{name},我来自{province}'.format(name='sky', province='湖南'))
print('我的名字是:{0},我来自{1},我的家乡是{1}'.format('sky', '湖南'))

name = 'Runoob'
print(f'Hello {name}')  # 替换变量
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/test_demo/test_06.py
我的名字是:sky,我来自湖南
我的名字是:sky,我来自湖南
我的名字是:sky,我来自湖南
我的名字是:sky,我来自湖南,我的家乡是湖南
Hello Runoob

Process finished with exit code 0
View Code

 

4a、字符串拼接、转义 , str.join(列表)、 str.split('_')

  示例代码如下:

#  字符串拼接、转义(\)
str1 = "自我介绍:\"我是sky,我来自湖南\" "
print(str1)

str2 = 'hello'
str3 = 'world'

str4 = str2 + str3
print(str4)

str_list = ['hello', 'python', 'hello', 'java']
temp = ' '.join(str_list)
print(temp)

str_var = 'hello_python_java_php'
temp_2 = str_var.split('_')
print(temp_2)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/demo_3.py
自我介绍:"我是sky,我来自湖南" 
helloworld
hello python hello java
['hello', 'python', 'java', 'php']

Process finished with exit code 0
View Code

 

  

随堂练习:

示例代码如下:

# -*- coding:utf-8 -*-
# Author:  Sky
# Email:   2780619724@qq.com
# Time:    2021/7/26 23:10
"""
基础必做题:
(作业提交形式:py文件。每一题请带上题目,再是代码。一定要代码执行成功之后,再上交py文件。)

1、题目:现在有字符串:str1 = 'python cainiao 666' ,请使用代码找出第 5 个字符
       请复制一份字符串,保存在变量 str_two 当中(赋值运算符)

2、题目:卖橘子的计算器(字符串转化)
        写一段代码,用户输入橘子的价格,和重量,计算出应该支付的金额!
      (提示:不需要校验数据,默认传入数字就可以了。使用input函数获取用户输入哦,并且input 得到的数据都是字符串类型)
       price = input("请输入价格")
       weight = input("请输入重量")

 3、题目:字符串综合演练 (字符串索引和切片。注意位置和索引的区别)
         my_hobby = "Never stop learning!"
        说明:“位置”指的是字符所处的位置(比如位置1,指的是第一个字符“N”);
        “索引”指的是字符的索引值(比如索引0, 代表的是第一个字符“N”);
        开始位置 ,是指字符串起始,即下标为0开始;末尾,是指字符串最后。

        截取从 位置2 ~ 位置6 的字符串(含 位置2和6)

        截取完整的字符串

        从 索引3 开始,每2个字符中取一个字符(含索引3,步长为2)

       截取字符串末尾两个字符

       字符串的倒序


4、题目:有字符串s如下
       s = 'python'
      请编写代码打印字符串s的第一个字符

      请编写代码打印字符串s的最后一个字符

5、题目:有字符串s如下
       s = '1234567890'
       请编写代码用切片的方式打印出'13579'

       请编写代码用切片的方式打印出'97531'

      请编写代码用切片的方式打印出'24680'

 6、题目:将"hello world"转为首字母大写"HELLO WORLD"

 7、题目: 将字符串"I Love Java" 变成"I Love Python"(替换)

"""




"""
1、题目:现在有字符串:str1 = 'python cainiao 666' ,请使用代码找出第 5 个字符
         请复制一份字符串,保存在变量 str_two 当中(赋值运算符)
"""
print('==============题目 1 ============')
str1 = 'python cainiao 666'
print(str1[4])

import copy
str_two = copy.copy(str1)
print(str_two)


print('==============题目 2 ============')
"""
2、题目:卖橘子的计算器(字符串转化)
        写一段代码,用户输入橘子的价格,和重量,计算出应该支付的金额!
      (提示:不需要校验数据,默认传入数字就可以了。使用input函数获取用户输入哦,并且input 得到的数据都是字符串类型)
       price = input("请输入价格")
       weight = input("请输入重量")
"""

price = float(input("请输入价格"))
weight = float(input("请输入重量"))
money = price * weight
print(money)

# price_1 = float(input("请输入价格"))
# weight_1 = float(input("请输入重量"))
# money_1 = eval('price_1 * weight_1')
# print(money_1)


print('==============题目 3 ============')
"""
3、题目:字符串综合演练 (字符串索引和切片。注意位置和索引的区别)
         my_hobby = "Never stop learning!"
        说明:“位置”指的是字符所处的位置(比如位置1,指的是第一个字符“N”);
        “索引”指的是字符的索引值(比如索引0, 代表的是第一个字符“N”);
        开始位置 ,是指字符串起始,即下标为0开始;末尾,是指字符串最后。

        截取从 位置2 ~ 位置6 的字符串(含 位置2和6)

        截取完整的字符串

        从 索引3 开始,每2个字符中取一个字符(含索引3,步长为2)

       截取字符串末尾两个字符

       字符串的倒序
"""

my_hobby = "Never stop learning!"

# 截取从 位置2 ~ 位置6 的字符串(含 位置2和6)
print(my_hobby[1:7])

# 截取完整的字符串
print(my_hobby[:])

# 从 索引3 开始,每2个字符中取一个字符(含索引3,步长为2)
print(my_hobby[3::2])

# 截取字符串末尾两个字符
print(my_hobby[-2:])

# 字符串的倒序
print(my_hobby[::-1])


print('==============题目 4 ============')
"""
4、题目:有字符串s如下
       s = 'python'
      请编写代码打印字符串s的第一个字符

      请编写代码打印字符串s的最后一个字符
"""
s = 'python'
print(s[0])
print(s[-1])


print('==============题目 5 ============')
"""
5、题目:有字符串s如下
       s = '1234567890'
       请编写代码用切片的方式打印出'13579'

       请编写代码用切片的方式打印出'97531'

      请编写代码用切片的方式打印出'24680'
"""
s = '1234567890'
print(s[0:len(s):2])

print(s[0:len(s):2][::-1])

print(s[1:len(s):2])


print('==============题目 6 ============')
"""
 6、题目:将"hello world"转为首字母大写"HELLO WORLD"
"""
s = "hello world"
print(s.upper())


print('==============题目 7 ============')
"""
7、题目: 将字符串"I Love Java" 变成"I Love Python"(替换)
"""
ss = "I Love Java"
temp = ss.replace('Java', 'Python')
print(temp)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/py43-day2-sky-20210726.py
==============题目 1 ============
o
python cainiao 666
==============题目 2 ============
请输入价格13.5
请输入重量2
27.0
==============题目 3 ============
ever s
Never stop learning!
e tplann!
g!
!gninrael pots reveN
==============题目 4 ============
p
n
==============题目 5 ============
13579
97531
24680
==============题目 6 ============
HELLO WORLD
==============题目 7 ============
I Love Python

Process finished with exit code 0
View Code

 

 

补充知识:

 

posted @ 2021-07-25 00:31  空-山-新-雨  阅读(134)  评论(0编辑  收藏  举报