Python 编程——字符串

一、认知

字符串 就是一系列字符。在 Python中,用引号引起来的都是字符串,其中引号可以是单引号,也可以是双引号。

>>> a = 'hello'
>>> print(a)
hello
>>> b = "westos"
>>> print(b)
westos
>>> c = 'what\'s'
>>> print(c)
what's
>>> d = "what's"
>>> print(d)
what's
>>> e = """
... 用户管理系统
... 1.添加用户
... 2.删除用户
... 3.显示用户
... ......
... """
>>> print(e)

用户管理系统
1.添加用户
2.删除用户
3.显示用户
......

>>> print(type(e))
<type 'str'>

二、字符串的特性

1.索引

索引从0开始而不是1

s = 'hello'
h e l l o
0 1 2 3 4
s[0]:h
s[1]:e
s[2]:l
s[3]:l
s[4]:o
s = 'hello'
print(s[0])   #打印第一个字符
print(s[4])   #打印第四个字符
print(s[-1])  #打印字符串的最后一个字符

2.切片

切片的原则 s[start:end:step] 从start开始到end-1结束,步长为step

>>> s ='hello'
>>> print(s[0:3])
hel
>>> print(s[0:4:2])
hl
>>> print(s[:])     #显示所有字符
hello
>>> print(s[:3])    #显示前3个字符
hel
>>> print(s[::-1])  #字符串的翻转
olleh
>>> print(s[1:])    #除了第一个字符之外,其他全部显示
ello

3.重复

>>> s = 'hello'
>>> print(s*10)
hellohellohellohellohellohellohellohellohellohello

4.连接

>>> s = 'hello'
>>> print('hello' + 'python')
hellopython

5.成员操作符

检测字符是不是在对应的变量里

>>> s = 'hello'
>>> print('he' in s)
True
>>> print('aa' in s)
False
>>> print('he' not in s)
False

6.\t:制表符

\t:在控制台输出一个制表符,协助我们在输出文本的时候在垂直方向保持对齐

在这里插入图片描述
在这里插入图片描述

6.\n:换行符

>>> print('hello\npython')
hello
python

7.:转译字符

>>> print('what\'s')
what's

题目要求:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样
的整数。

示例:

示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数

num = input('请输入数字:')
print(num == num[::-1])

三、字符串常用方法

1.大小写

>>> 'Hello'.istitle()     #检测是不是标题
True
>>> 'hello'.istitle()     #检测是不是标题
False
>>> 'hello'.isupper()     #检测是不是全部为大写
False
>>> 'hello'.upper()       #转换为大写
'HELLO'
>>> 'hello'.islower()     #检测是不是全部为小写
True
>>> 'HELLO'.lower()       #转换为小写
'hello'
>>> 'hello'.title()       #转换为标题
'Hello'

2.字符串开头和结尾的匹配

.endswith() ##是不是以什么什么结尾的

filename = 'hello.log'
if filename.endswith('.log'): 
    print(filename)
else:
    print('error.file')

.startswith() ##是不是以什么什么开头的

url1 = 'file:///mnt'
url2 = 'lftp://172.25.254.250/pub'
url3 = 'https://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('爬取网页')
else:
    print('不能爬取网页')

4.去除字符串左右两边的空格

注意:去除左右两边的空格,空格为广义的空格 包括:\n \t

>>> s = '      hello      '
>>> s
'      hello      '
>>> s.lstrip()           #从左边去掉空格
'hello      '
>>> s.rstrip()           #从左边去掉空格
'      hello'
>>> s = '\n\thello      '
>>> s
'\n\thello      '
>>> s.strip()            #去掉全部的空格
'hello'

()可以定义内容

>>> s = 'helloh'
>>> s.strip('h')         #去掉全部的h
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')       #从左边去掉he
'lloh'

5.判断字符类型

>>> print('1234'.isdigit())        ##是不是全为数字
True
>>> print('reqfeq'.isalpha())      ##是不是全为字母
True

注意:只要其中有一个元素不满足,就返回False

练习题:

变量名是否合法:
1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头
s = ‘hello@’

1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

提示:
1.变量名的第一个字符是否为字母或下划线
2.如果是,继续判断 ---->4
3.如果不是,报错
4.依次判断除了第一个字符之外的其他字符,是否为字母数字或下划线

while True:
    s = input('请输入要判断的变量名:')
    if s == 'exit':
        print('退出')
        break
    pass
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not (i.isalnum() or i == '_'):
                print('%s不是变量名' %(s))
        else:
            print('%s是合法变量名' %(s))
            break
    else:
        print('%s首要条件不满足,不是变量名\n error' %(s))

6.字符串的对齐

>>> print('学生管理系统'.center(30))        #两边各留30个空间长度
      学生管理系统      
>>> print('学生管理系统'.center(30,'*'))    #两边各留30个空间长度,并用*占位
******学生管理系统******
>>> print('学生管理系统'.center(30,'@'))
@@@@@@学生管理系统@@@@@@
>>> print('学生管理系统'.ljust(30,'*'))
学生管理系统************
>>> print('学生管理系统'.rjust(30,'*'))
************学生管理系统

7.字符串的搜索和替换

>>> s = 'hello world hello'
>>> print(s.find('hello'))        #find找到字符串,并返回最小的索引
0
>>> print(s.find('world'))
6
>>> print(s.rfind('hello'))      #find从右边以hello为基准找到字符串hello,并返回最小的索引
12
>>> print(s.replace('hello','westos'))    #替换字符串中的'hello' 为'westos'
westos world westos

7.字符串的统计

>>> print('hello'.count('l'))     #统计hello里有几个l
2
>>> print('hello'.count('ll'))    #统计hello里有几个ll
1
>>> print(len('westos'))          #统计westos的字符串长度
6

8.字符串的分离和连接

s = '172.25.254.250'
s1 = s.split('.')              #以.为分隔符,将字符串分离
print(s1)
print(s1[::-1])

执行脚本
['172', '25', '254', '250']
['250', '254', '25', '172']

连接,通过指定的连接符,连接每个字符串

date = '2019-3-13'
date1 = date.split('-')
print(date1)
print(''.join(date1))
print('/'.join(date1))

执行脚本
['2019', '3', '13']
2019313
2019/3/13
>>> print('@'.join('hello'))
h@e@l@l@o

练习题:

  1. 设计一个程序,帮助小学生练习10以内的加法

    详情:
    - 随机生成加法题目;
    - 学生查看题目并输入答案;
    - 判别学生答题是否正确?
    - 退出时, 统计学生答题总数,正确数量及正确率(保留两位小数点);

import random
num = int(input('输入题目数量:'))
true = 0
for i in range(0,num):
    que1 = random.randint(1,9)
    que2 = random.randint(1,9)
    print('%d+%d=?' %(que1,que2))
    sum = que1 + que2
    student = int(input('输入答案:'))
    if sum == student:
        print('答案正确')
        true += 1
    else:
        print('答案错误')
else:
    print('true:%d' %(true))
    zql = (true / num) * 100
    print('答题总数:%d,正确数量:%d,正确率为:%.2f%%' %(num,true,zql))

2.小学生算术能力测试系统:
设计一个程序,用来实现帮助小学生进行百以内的算术练习,
它具有以下功能:
提供10道加、减、乘或除四种基本算术运算的题目;
练习者根据显示的题目输入自己的答案,
程序自动判断输入的答案是否正确并显示出相应的信息。

import random
op = ['+','-','*','/']

i = 0
j = 0
while True:
    a = random.randint(0,100)
    b = random.randint(0,100)
    s = random.choice(op)
    print('%d %s %d = ?' %(a,s,b))
    ans = input('请输入答案(e/退出):')
    if s == '+':
        result = a + b
    if s == '-':
        result = a - b
    if s == '*':
        result = a * b
    if s == '/':
        result = a / b
    if ans == str(result):
        print('答案正确')
        i += 1
        j += 1
    elif ans == 'e':
        print('退出程序')
        break
    else:
        print('答案错误')
        j += 1
percent = i / j * 100
print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%' %(i,j,percent))

猜你喜欢

转载自blog.csdn.net/weixin_44209804/article/details/88555843