Python之字符串的特性及常用方法

字符串的特性

切片: (索引是从0开始)
s='hello'
print(s[0])
print(s[4])
print(s[-1])   #拿出最后一个字符

h
o
o
截取s[start:stop:step] 从start开始到stop结束,步长为step
print(s[0:3])
print(s[0:4:2])
print(s[:]) #显示所有的字符
print(s[:3]) #显示前3个字符 
print(s[1:]) #除了第一个字符之外的其他全部字符
print(s[::-1]) #字符串的翻转

hel
hl
hello
hel
ello
olleh
重复
print(s * 10)

hellohellohellohellohellohellohellohellohellohello
连接
print('hello ' + 'python')

hellopython
成员操作符
print('he' in s)
print('aa' in s)
print('he' not in s)

True
False
False
for循环遍历
for i in s:
    print(i)
    
h
e
l
l
o
-------------练习1------------

判断一个整数是否是回文数。

# nmb=input('请输入一个数:')
# nmbs=nmb[ : :-1]
# if(nmb == nmbs):
#     print('此数是回文数')
# else:
#     print('此数不是回文数')

不用字符串特性

    # nmb = input('输入数字:') 
    # c = len(nmb)
    # b = int(c / 2)
    # a = 0
    # for j in range(b):
    #     if (nmb[a] != nmb[c - 1 - a]):
    #         print('不是回文数')
    #         break
    # else:
    #     print('是回文数')

字符串的常用方法

判断是否是标题、大写、小写、以及大小写、标题的转换、将字符串的首字母大写其余字母全部小写
str.istitle()
str.isupper()
str.islower()
str.title() #将字符串中的所有单词的首字母大写,其余字母全部小写;单词以任何标点符号区分的
str.captialize() #将字符串的首字母大写,其余字母全部小写
str.upper()
str.lower()

   >>> 'Hello'.istitle()
    True
    >>> 'hello'.istitle()
    False
    >>> 'hello'.isupper()
    False
    >>> 'Hello'.isupper()
    False
    >>> 'HELLO'.isupper()
    True
    >>> 'hello'.islower()
    True
    >>> 'HELLO'.islower()
    False
    >>> 'HELLO'.lower()
    'hello'
    >>> 'hello'.upper()
    'HELLO'
    >>> 'hello'.title()
    'Hello'

前缀和尾缀的匹配

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

url = 'https://172.25.254.250/index.html'
if url.startswith('http://'):
    print('爬取网页')
else:
    print('不能爬取')
    
不能爬取

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

    >>> s = '       hello          '
    >>> s
    '       hello          '
    >>> s.lstrip()
    'hello          '
    >>> s.rstrip()
    '       hello'
    >>> s.strip()
    'hello'
    >>> s = '\t\thello    \n\n'
    >>> s
    '\t\thello    \n\n'
    >>> s.strip()
    'hello'
    >>> s.rstrip()
    '\t\thello'
    >>> s.lstrip()
    'hello    \n\n'
    >>> s = 'helloh'
    >>> s.strip('h')
    'ello'
    >>> s.strip('he')
    'llo'
    >>> s.lstrip('he')
    'lloh'
字符串的判断

str.isdigit() #全数字
str.isalpha() #全字母
str.isalnum() #只有数字和字母

-------------练习--------------

判断变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母和或者下划线开头

sname = input('请输入变量名:')
if not (sname[0].isalpha()) or sname[0] == '_':
    print('illegal')
else:
    a =0
    for i in sname:
        if sname[a] =='_' or sname[a].isalnum():
            a += 1
        else:
            print('illegal')
            break
    else:
        print('合法')

----------------OR--------------------
    # while True:
    #     s = input('变量名:')
    #     if s == 'exit':
    #         print('exit')
    #         break
    #     if s[0].isalpha() or s[0] == '_':
    #         for i in s[1:]:
    #            if not(i.isalnum() or i == '_'):
    #                print('%s变量名不合法' %(s))
    #                break
    #
    #         else:
    #             print('%s变量名合法' %(s))
    #
    #     else:
    #         print('%s变量名不合法' %(s))

字符串的对齐

print('jjj'.center(30))
print('jjj'.center(30,'*'))
print('jjj'.ljust(30,'#'))
print('jjj'.rjust(30,'$'))

             jjj              
*************jjj**************
jjj###########################
$$$$$$$$$$$$$$$$$$$$$$$$$$$jjj

字符串的搜索和替换

s = 'hello world hello'

#find找到子字符串,并返回最小的索引

print(s.find('hello'))
print(s.find('world'))
print(s.rfind('hello'))

#替换字符串中的hello为westos

print(s.replace('hello','westos'))

字符串的统计及串长

print('hello'.count('l'))   2
print('hello'.count('ll'))   1

print(len('westosssss'))  10

字符串的分割和连接

#分割 通过指定的连接符进行

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

date = '2019-05-24'
date1 = date.split('-')
print(date1)

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

print(''.join(date1))
print('/'.join(date1))
print('~~'.join('hello'))

字符串库

import string
#string库
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
-------------练习--------------

#小米笔试练习:给定一个句子(只有字母和空格,单词用一个空格隔开)将句子中单词的位置反转

# while True:
#     str = input('请输入句子: ')
#     if str == 'exit':
#         exit()
#     else:
#         str1 = str.split(' ')
#         print(' '.join(str1[::-1]))
-------------练习---------------

#设计程序:帮助小学生练习10以内的加法
#detail:随机生成加法题目,学生查看题目并输入答案,判别,退出统计答题总数,正确数,正确率

# import random
# a=0
# b=0
# while True:
#     str = input('答题:y or n  ')
#     if str == 'n':
#         print('答题总数为%d,正确数为%d,正确率为%.2f' %(a,b,b/a))
#         exit()
#     else:
#         nmb1 = random.randint(0, 10)
#         nmb2 = random.randint(0, 10)
#         jug = nmb1 + nmb2
#         print('%d + %d=' % (nmb1, nmb2), end='')
#         ans = int(input())
#         if ans == jug:
#             b+=1
#             print('正确')
#         else:
#             print('错误')
#         a+=1
#
------------练习-------------

#设计程序:百以内的算术练习
#功能:提供10道±*/题目,练习者输入答案,程序自动判断并显示

import random
opt = ['+', '-', '*', '/']
print('开始答题:')
for i in range(10):
    nmb1 = random.randint(0, 100)
    nmb2 = random.randint(0, 100)
    f = random.choice(opt)
    print('%d%s%d= ' % (nmb1, f, nmb2),end='')
    ans = int(input( ))
    if (f == opt[0]):
        jug = nmb1 + nmb2
    elif (f == opt[1]):
        jug = nmb1 - nmb2
    elif (f == opt[2]):
        jug = nmb1 * nmb2
    else:
        jug = nmb1 / nmb2
    if ans == jug:
        print('正确')
    else:
        print('错误')
------------练习-------------

#如何快速生成验证码

import random
import string

code_str = string.ascii_letters + string.digits
# code_str1 = string.ascii_lowercase
# code_str2 = string.ascii_uppercase
print(code_str)

def gen_code(len=4):
    #     code = ''
    #     for i in range(len):
    #         new_s = random.choice(code_str)
    #         code += new_s
    #
    #     return code
    return ''.join(random.sample(code_str, len))
 
print([gen_code() for i in range(1000)])
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值