Python学习————字符串类型

一、定义

msg='hello' # msg=str('msg')
print(type(msg))

二、类型转换

str可以把任意其他类型都转成字符串

res=str({'a':1})
print(res,type(res))

三、使用:内置方法

3.1按索引取值(正向取+反向取)

正向取

msg = 'hello world'
print(msg[0])
print(msg[4])

h
o

反向取

msg = 'hello world'
print(msg[-1])

d

只能取

msg[0]='H'

3.2、切片:索引的拓展应用,从一个大字符串中拷贝出一个子字符串

顾头不顾尾

msg = 'hello world'
res=msg[0:5] #x
print(res)
print(msg)

hello
hello world

步长

msg = 'hello world'
res=msg[0:5:2] # 0 2 4
print(res) 

hlo

反向步长(了解)

msg = 'hello world'
res=msg[5:0:-1]
print(res) 

olle

正常取值

msg = 'hello world'
res=msg[:] # res=msg[0:11]
print(res)

hello world

反向取值

msg = 'hello world'
res=msg[::-1] # 把字符串倒过来
print(res)

dlrow olleh

3.3、长度len

msg='hello world'
res = len(msg)  # len用于计算字符串的长度,输出的类型为str
print(msg,type(msg))

hello world <class 'str'>

3.4、成员运算in和not in 判断一个子字符串是否存在于一个大字符串中

print("alex" in "alex is sb")

True
print("alex" not in "alex is sb")

True
print(not "alex" in "alex is sb") # 不推荐使用

True

3.5、移除字符串左右两侧的符号strip

默认去掉的空格

msg='      egon      '
res=msg.strip()
print(msg) # 不会改变原值
print(res) # 是产生了新值

      egon      
egon

可以去掉指定的字符

msg='****egon****'
print(msg.strip('*'))

egon

msg='**/*=-**egon**-=()**'
print(msg.strip('*/-=()'))

egon

应用

inp_user=input('your name>>: ').strip() # inp_user=" egon"
inp_pwd=input('your password>>: ').strip()
if inp_user == 'egon' and inp_pwd == '123':
    print('登录成功')
else:
    print('账号密码错误')

3.6、切分split:把一个字符串按照某种分隔符进行切分,得到一个列表

默认分隔符是空格

info='egon 18 male'
res=info.split()
print(res)

['egon', '18', 'male']

指定分隔符

info='egon:18:male'
res=info.split(':')
print(res)

['egon', '18', 'male']

指定分隔次数(了解)

info='egon:18:male'
res=info.split(':',1)
print(res)

['egon', '18:male']

3.7、循环

info='egon:18:male'
for x in info:
    print(x)
    
e
g
o
n
:
1
8
:
m
a
l
e

四、 需要掌握

1、strip,lstrip,rstrip

msg='***egon****'
print(msg.strip('*'))  #strip:移除字符串中指定的符号
print(msg.lstrip('*')) #lstrip:移除字符串左侧指定的符号
print(msg.rstrip('*')) #rstrip:移除字符串右侧指定的符号

2、lower,upper

msg='AbbbCCCC'
print(msg.lower()) #lower:把字符串中所有字母变成小写字母
print(msg.upper()) #lower:把字符串中所有字母变成小写字母

3、startswith,endswith

print("alex is sb".startswith("alex"))
print("alex is sb".endswith('sb'))

4、format 格式化输出

其实就是format()后面的内容,填入大括号中(可以按位置,或者按变量)

res='我的名字是 {} 我的年龄是 {}'.format('egon',18)
print(res) 

我的名字是 egon 我的年龄是 18

5、split,rsplit:将字符串切成列表

info="egon:18:male"
print(info.split(':',1)) # ["egon","18:male"] #split:从左往右切分
print(info.rsplit(':',1)) # ["egon:18","male"] #rsplit:从右往左切分

6、join: 把列表拼接成字符串

按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串

l=['egon', '18', 'male']
res=l[0]+":"+l[1]+":"+l[2]
res=":".join(l) # 按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串
print(res)

egon:18:male

7、replace 替换

msg="you can you up no can no bb"
print(msg.replace("you","YOU",))

YOU can YOU up no can no bb

自定义替换

msg="you can you up no can no bb"
print(msg.replace("you","YOU",1))
YOU can you up no can no bb

8、isdigit 判断字符串是否由纯数字组成

print('123'.isdigit())

True

print('12.3'.isdigit())

False
age=input('请输入你的年龄:').strip()
if age.isdigit():
    age=int(age) # int("abbab")
    if age > 18:
        print('猜大了')
    elif age < 18:
        print('猜小了')
    else:
        print('才最了')
else:
    print('必须输入数字,傻子')

五、了解

1、find,rfind,index,rindex,count

find :找到返回起始索引

msg = 'hello egon hahaha'
print(msg.find('e')) # 返回要查找的字符串在大字符串中的起始索引
print(msg.find('egon'))

1
6

index:

msg = 'hello egon hahaha'
print(msg.index('e'))
print(msg.index('egon'))

1
6

返回-1,代表找不到

msg = 'hello egon hahaha'
print(msg.find('xxx')) # 返回-1,代表找不到

-1

index :抛出异常

print(msg.index('xxx')) # 抛出异常

    print(msg.index('xxx')) # 抛出异常
ValueError: substring not found

count:计算字符串在大字符串中出现的次数

msg='hello egon hahaha egon、 egon'
print(msg.count('egon'))

3

2、center,ljust,rjust,zfillcenter:在center内容中间添加内容

print('egon'.center(50,'*'))

***********************egon***********************

ljust:在ljust内容左边添加内容

print('egon'.ljust(50,'*'))

egon**********************************************

rjust:在ljust内容右边添加内容

print('egon'.rjust(50,'*'))

**********************************************egon

zfill:在zfill内容中加到指定个数

print('egon'.zfill(10))

000000egon

3.expandtabs

设置制表符代表的空格数

msg='hello	world'
print(msg.expandtabs(2)) # 设置制表符代表的空格数为2

hello world

4.captalize、swapcase、title

captalize:一段字符串的首个字母大写,其余小写

print("hello world egon".capitalize())

Hello world egon

swapcase:一段字符串的首个字母小写,其余大写

print("Hello WorLd EGon".swapcase())

hELLO wORlD egON

title:每个单词的首字母大写,其余小写

print("hello world egon".title())

Hello World Egon

5.is系列

.isdigit():判断是否全部都是纯数字类型

print('123'.isdigit())

True

.islower():判断是否全部都是小写字母

print('abc'.islower())

True

.isupper():判断是否全部都是大写字母

print('ABC'.isupper())

True

.istitle():判断是否是单词首个字母大写

print('Hello World'.istitle())

True

.isalnum():判断是否由数字或字母组成

print('123123aadsf'.isalnum()) # 字符串由字母或数字组成结果为True

True

.isalpha():判断是否全部由字母构成

print('ad'.isalpha()) # 字符串由由字母组成结果为True

True

.isspace():判断是否全部由空格构成

print('     '.isspace()) # 字符串由空格组成结果为True

True

.isidentifier():判断是否可以定义为变量名

print('print'.isidentifier())
print('age_of_egon'.isidentifier())
print('1age_of_egon'.isidentifier())

True
True
False   # 变量名不能以数字开头

6.数字系列的识别

先定义表示同一个数字的4个不同方法:

num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字

isdigit只能识别:num1、num2

print(num1.isdigit()) # True
print(num2.isdigit()) # True
print(num3.isdigit()) # False
print(num4.isdigit()) # False

True
True
False
False

isnumberic可以识别:num2、num3、num4

print(num2.isnumeric()) # True
print(num3.isnumeric()) # True
print(num4.isnumeric()) # True

True
True
True

isdecimal只能识别:num2

print(num2.isdecimal()) # True
print(num3.isdecimal()) # False
print(num4.isdecimal()) # False

True
False
False

PS:部分内容 参考https://www.cnblogs.com/xuexianqi/p/12456287.html

原文地址:https://www.cnblogs.com/x945669/p/12458497.html