Python菜鸟编程第二课之字符串

Python菜鸟编程第二课之字符串

1. 字符串

Python的字符串有单引号、双引号以、三个单引号以及三个双引号。

demo:

name = "HangZhou"
area = 'Gongshu'
history = "5000"
famous_person = """苏轼,许仙,白素贞"""
capticalof = '''吴越,南宋'''

print(type(name), type(area), type(history), type(famous_person), type(capticalof))

sent = "I'm Lilei"
sent2 = 'He is my "brother",he said'  
print(sent)
print(sent2)
运行结果:
<class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>
I'm Lilei
He is my "brother",he said

单引号双引号不允许换行,使用是需要注意匹配关系。假如要换行,三单引号或者三双引号都可以。

1.1 字符串的拼接

拼接需要基于同一种数据类型

a = "hello"
b = "world"
print(a + b)
c = ["Hello"]
d = [",world."]
print(c + d)
运行结果:
helloworld
['Hello', ',world.']

1.2重复

a = "City College"
print(a * 3)
运行结果:
City CollegeCity CollegeCity College

1.3索引

字符串的索引,假如有一个sr=“PYTHON”,从左到右PYTHON所对应的索引为012345。而从右到左,所对应的索引为-6,-5,-4,-3,-2,-1。

PYTHON
012345
-6-5-4-3-2-1

练习题:

将字符串所有字符遍历输出

sr = "Python"
for i in sr:
    print(i,end=" ")
    
#或者

for i in range(len(sr)):
    print(sr[i],end=" ")
运行结果:
P y t h o n 
  • 切片

有一个字符串str1 = “xxxxxxxxxxxxxxxxx”

str2=str1[start:end:step]#start起始位置,end终止位置,step步长。类似于range。

demo:

str1 = "abcdefghijklmn"
print(str1)
print(str1[::-1])  # 步长为-1时,逆序输出
print(str1[:8], "\t")
print(str1[:8:2], "\t")
print(str1[3:8], "\t")
print(str1[3:8:2], "\t")
运行结果:
abcdefghijklmn  str1的字符串
nmlkjihgfedcba  str1逆序输出
abcdefgh 	    从索引为0开始到索引为7的元素
aceg 			从索引为0开始到索引为7的元素,步长为2,中间跳跃1个元素	
defgh 			从索引为3开始到索引为7的元素
dfh 			从索引为3开始到索引为7的元素,步长为2,中间跳跃1个元素

切片要点,取前不取后。

1.4大小写转换

函数名描述
str.lower()全部转化成小写
str.upper()全部转化成大写
str.swapcase()大小写相互转换
str.title()转化成标题的形式
str.capitalize()首字母大写

demo:

str1 = "life is short,you NEED pYtHOn"
print(str1.lower())
print(str1.upper())
print(str1.swapcase())
print(str1.title())
print(str1.capitalize())
运行结果:
life is short,you need python
LIFE IS SHORT,YOU NEED PYTHON
LIFE IS SHORT,YOU need PyThoN
Life Is Short,You Need Python
Life is short,you need python

1.5字符串的格式对齐输出

函数名描述
str.center([len],[填充符号])居中对齐
str.ljust([len],[填充符号])靠左对齐
str.rjust([len],[填充符号])靠右对齐
str.zfill(len)靠右对齐,默认填充0

demo:

str1 = "life is short,you need python"
print("str1的长度为:",len(str1))
print(str1.center(41, '#'))
print(str1.ljust(41,'#'))
print(str1.rjust(41,'#'))
print(str1.zfill(41))
运行结果:
str1的长度为: 29
######life is short,you need python######
life is short,you need python############
############life is short,you need python
000000000000life is short,you need python

1.6删除指定字符

函数名描述
str.strip()删除左右两边的字符
str.lstrip()删除左两边的字符
str.rstrip()删除右两边的字符

demo:

str1 = "######life is short,you need python######"
print(str1.strip("#"))
print(str1.lstrip("#"))
print(str1.rstrip("#"))
运行结果:
life is short,you need python
life is short,you need python######
######life is short,you need python

1.7计数

使用count()函数来计数

demo:

str1 = "life is short,you need python"
print(str1.count('o'))
print(str1.count('o',2,7))
print(str1.count('o',9,17))
运行结果:
3
0
2

后面的数字用来指定范围,取前不取后。

1.8字符串搜索定位和替换

主要使用find()函数、index()等函数

函数名描述
find()查找元素并返回第一次出现的元素索引值。假如查找不到,返回-1。
index()查找元素并返回第一次出现的元素索引值。假如查找不到,报错。
rindex()从右往左查找
replace([现有],[替换])替换某个值

demo:

str1 = "life is short,you need python"
print(str1.find('e'))
print(str1.find('e',19,25))
print(str1.find('a'))

print(str1.index('e'))
print(str1.index('e',19,25))
print(str1.index('z'))

print(str1.replace('you need', 'i use'))
print(str1.replace('t', 'T' ))
print(str1.replace('t', 'T', 1))#指定替换的次数
运行结果:
3
19
-1
3
9
ValueError: substring not found
    
life is short,i use python
life is shorT,you need pyThon
life is shorT,you need python

1.9字符串条件判断

函数名描述
isalnum()判断字符是否由字母或者数字组成
isalpha()判断字符是否全由字母组成
isdigit()判断字符是否全由数字组成
islower()判断字符是否全是小写
isupper()判断字符是否全是大写
istitle()判断字符是否符合标题,即首字母大写
isspace()判断字符是否全是空白字符
isascii()判断字符是否为阿斯克码
isdecimal()判断字符串是否只包含十进制字符。
isidentifier()判断字符串是否是字母开头
isnumeric()如果字符串中的所有字符都是数字字符,并且至少有一个字符,则返回true
isprintable()判断是否字符串中的所有字符都可打印或字符串为空

demo:

#数字混合字符串判断
str1 = "asfa456"
print(str1.isalnum())
print(str1.isalpha())
print(str1.isdigit())
#数字字符串判断
str2 = "456"
print(str2.isalnum())
print(str2.isalpha())
print(str2.isdigit())
#字母字符串判断
str3 = "sda"
print(str3.isalnum())
print(str3.isalpha())
print(str3.isdigit())
运行结果:
#数字混合字符串判断
True
False
False
#数字字符串判断
True
False
True
#字母字符串判断
True
True
False

1.10制表符的转化

使用expandtabs()函数。

expandtabs():返回字符串中的 tab 符号(’\t’)转为空格后生成的新字符串。通常可用于表格格式的输出

demo:

info ="name\tage\temail\nlittlefive\t22\t994263539@qq.com\njames\t33\t66622334@qq.com"
print(info.expandtabs(10))
运行结果:
name      age       email
littlefive          22        994263539@qq.com
james     33        66622334@qq.com

1.11字符串的分割变换

函数名描述
join()将制定字符插入到元素中
split()以指定字符分割字符串并去除该字符
partition()以指定字符分割字符串并保留该字符串

demo:

str1="life is short,you need python"
str2='*'
l1=["i","love","python"]
print(str2.join(str1))
print('*'.join(l1))
print(str1.split('o'))
print(str1.split('o',2))
print(str1.partition('o'))
运行结果:
l*i*f*e* *i*s* *s*h*o*r*t*,*y*o*u* *n*e*e*d* *p*y*t*h*o*n  #将前一个字符串加入到后一个字符串中
i*love*python
['life is sh', 'rt,y', 'u need pyth', 'n']
['life is sh', 'rt,y', 'u need python']
('life is sh', 'o', 'rt,you need python')

1.12 ASCII值和字符的转化

练习题:

利用ASCII,打印a-z

for i in range(ord('a'),ord('z')+1):
    print(chr(i),end=" ")
运行结果:
a b c d e f g h i j k l m n o p q r s t u v w x y z 

练习题:

随机输出4位数字字母验证码。

import string
import random
str1=list(string.digits+string.ascii_letters)
random.shuffle(str1)
finall_str1=""
for i in range(4):
    finall_str1=finall_str1+str1[i]
print("验证码为:",finall_str1)
运行结果:
验证码为: 3UvI
  • 进制的转化输出
for i in range(8):
    print(oct(i),end=" ")
print("")
for i in range(16):
    print(hex(i),end=" ")
print("")
print('%o'% 17)
print('%x'% 17)
运行结果:
0o0 0o1 0o2 0o3 0o4 0o5 0o6 0o7 
0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 
21
11

博主qq:1031748759.欢迎批评指正!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值