Python学习(字符串)

一、字符串

1.1 什么是字符串
  • 用引号引起来的一串字符
  • 用引号来创建字符串
    • 单引号
    • 双引号
    • 三单引号
    • 三双引号

注:
单引号和双引号使用时要注意匹配关系,且不可以换行
如果要换行,使用三单引号或者三双引号

str1 = 'aaa'
str2 = "bbb"
str3 = '''ccc'''
str4 = """ddd"""
sent = "I'm Lilei"
sent2 = '"He is my brother",he said.'
1.2 字符串的运算及常见操作
拼接 +

基于同一种数据类型

a = 'Hello'
b = ',Python'
print(a + b)
#结果:Hello,Python
重复 *
a = 'Hello'
print(a * 3)
#结果:HelloHelloHello
索引(偏移)

sr[ ]

索引:下标从0开始

012345
Python
sr = 'Python'
for i in range(len(sr)):
    print(sr[i],end=" ")	#P y t h o n
print()
for j in sr:
    print(j,end=" ")		#P y t h o n
切片

sr [ : ]、sr[ : : ]

sr = "Life is short,you need python."
print(sr[:4])		#Life
print(sr[23:-1])	#python
print(sr[1:6:2])	#iei
print(sr[::-1])		#.nohtyp deen uoy,trohs si efiL
大小写转化
  • sr.lower():转小写
  • sr.upper():转大写
  • sr.swapcase():大小写互换
  • sr.title():转为标题的形式
  • sr.capitalize():首字母大写
sr = "Life is short,you need python."
print(sr.lower())       #life is short,you need python.
print(sr.upper())       #LIFE IS SHORT,YOU NEED PYTHON.
print(sr.swapcase())    #lIFE IS SHORT,YOU NEED PYTHON.
print(sr.title())       #Life Is Short,You Need Python.
print(sr.capitalize())  #Life is short,you need python.
字符串的格式输出对齐
  • sr.center([len],[填充字符]):居中对齐
  • sr.ljust([len],[填充字符]):居左对齐
  • sr.rjust([len],[填充字符]):居右对齐
  • sr.zfill([len]):居右对齐,默认填充0
sr = "Life is short,you need python."
print(sr.center(41,"*"))    #******Life is short,you need python.*****
print(sr.ljust(41,"*"))     #Life is short,you need python.***********
print(sr.rjust(41,"*"))     #***********Life is short,you need python.
print(sr.zfill(41))         #00000000000Life is short,you need python.
删除指定字符
  • sr.strip([字符]):默认删除空格
  • sr.lstrip([字符]):默认删除空格
  • sr.rstrip([字符]):默认删除空格
sr = '\n\t******Life is short,you need python.*****\t\n'
sr1 = sr.strip()
print(sr1)                  #******Life is short,you need python.*****
print(sr1.lstrip('*'))      #Life is short,you need python.*****
计数
  • sr.count(字符,[start],[stop])
sr = "Life is short,you need python."
print(sr.count('o'))           #3
print(sr.count('o',9,17))      #2
搜素定位和替换
  • sr.find(字符,[start],[stop]):查找元素并返回第一次出现的元素的索引值,查找不到,返回-1
  • sr.index(字符,[start],[stop]):查找元素并返回第一次出现的元素的索引值,查找不到,报错
  • sr.rindex(字符,[start],[stop]):从右往左查找
  • sr.replace([现有],[替新],[count]):替换指定元素
sr = "Life is short,you need python."
print(sr.find('e'))                 #3
print(sr.find('e',19,25))           #19
print(sr.find('z',19,25))           #-1
print(sr.index('e'))                #3
print(sr.index('e',19,25))          #19
print(sr.rindex('e'))               #20
print(sr.replace(' ',''))           #Lifeisshort,youneedpython.
print(sr.replace('t','T',1))        #Life is shorT,you need python.
条件判断
  • isalnum():判断字符串由字母或数字组成
  • isalpha():判断字符串仅由字母组成
  • isdigit():判断字符串仅由数字组成
a = 'asd124'
b = '666'
c = 'abc'
print(a.isalnum())          #True
print(b.isdigit())          #True
print(c.isalpha())          #True
制表符的转化
  • sr.expandtabs()
字符串的分割变换
  • join():将指定字符插入到元素之间
  • sr.split([字符],[count]):以指定字符分割字符串并去除该字符
  • sr.partition(字符):以指定字符分割字符串并保留该字符
sr = "Life is short,you need python."
print('+'.join(sr))     #L+i+f+e+ +i+s+ +s+h+o+r+t+,+y+o+u+ +n+e+e+d+ +p+y+t+h+o+n+.
li = ["I ","Love ","Python."]
print(''.join(li))      #I Love Python.
print(sr.split('o'))    #['Life is sh', 'rt,y', 'u need pyth', 'n.']
print(sr.split('o',2))  #['Life is sh', 'rt,y', 'u need python.']
print(sr.partition('o'))#('Life is sh', 'o', 'rt,you need python.')
ASCII值和字符的转化

chr():数字转化为字符

ord():字符转化为数字

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 

拓展:
string模块

import string
print(string.ascii_letters)     #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase)   #abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase)   #ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)            #0123456789
print(string.hexdigits)         #0123456789abcdefABCDEF
print(string.octdigits)         #01234567
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值