字符串类型内置方法

一、字符串类型内置方法(str)

1、用途:描述性质的东西,如人的名字、单个爱好、地址、国家等

2、定义:使用''、""、"''"

* unicode 编码的字符串#

* b'101':二进制编码的字符#

* r' ':原生字符串,也就是说' '这是普通的两个字符,并没有换行的意思

s1= str(1.1)
s2 = str([1,2,3]) #把列表转换成字符串
print(type(s1))
print(type(s2))

输出结果为

<class 'str'>

<class 'str'>

3、常用的操作+内置方法

1、按索引取值

2、切片

3、长度len、

4、成员运算in、not in

5、移除空白

6、切分split

7、循环

1.按索引取值(只可取,不可改变)

str索引取值

mag = "hello wang"
print(mag[4])
print(mag[-2])

l

n

2、切片(顾头不顾尾、步长)(索引切片)

# 2、切片(顾头不顾尾、步长)
#c
mag = 'hello wang'
print(mag[3:])
print(mag[3:8])
print(mag[3::2])# 切片3到最后,步长2
print(mag[-5:-2]) #wa

3、长度len

# 长度len
nag = "hello wanag"
print(len(nag))   #输出字符所占的长度

输出结果为 11

4、成员运算符in not in(判断字符是否在字符串当中)

# 4、成员运算符in not in
mag = "wang yang jiayi zhuang zhao"
print('wang' in mag)  #True
print('zhuang' not in mag) #False
print(not'jiayi'in mag) #False

5、移除空白或者字符strip()(变量名.strip("需要去除的"))

# 5、移除空白或者字符strip()
name = '   wan g'
print(name.strip())
#输出wan g  去掉’两边‘的空格

name = 'wan'
print(name.strip('n')) #wa
# strip()默认为' ',并且不修改原值,新创空间

# 应用场景
pwd = input('password:')
if pwd.strip() == '123':
#     print("输入成功")
print('#$wang*'.strip('#$*')) #也可在输出中直接去掉

6、切分split() (变量名.split(在这个字符的地方截开))

# 切分split
info = 'wang;love;meony'
print(info.split(';'))# 以分号结尾把字符串用,截开
print(info.split('n'))#以n结尾把字符串以,截开4
print(info.split(';',1)) #用分号结尾的地方把字符串用,截开。后面的1是直截取一次。从左到右。

7、循环

#7、循环
mag = 'hello wang'
# for i in mag:
#     print(i)
print(mag.strip('g'))# 突然想到去掉最后一个字母,用刚刚上面的内容

1.2 需要掌握

1.lstrip和rstrip (只移除左边的、只移除右边的)

2.lower()和upper() (所有字母都小写)(所有字母都大写)

3.startswith()和endswith () (以...开头、以...结尾)

4.rsplit()(从右边开始切割)

5.join()链接联和。用于将序列中的元素以指定的字符连接生成一个新的字符串。

6.replace()替换

7.isdigit()是否纯数字

1.lstrip()和rstrip

#1.lstrip()和人rstrip
name = '&&gihxkj&&'
print(name.lstrip('&'))
#从左边开始移除,右边的不管
name = '&&gihxkj&&'
print(name.rstrip('&'))
#从右边开始移除,右边的不管

2.lower()和upper() (所有字母小写,所有字母大写)

#2.lower()和upper()
name = 'wanG'
print(name.lower())
print(name.upper())

3.startswith()和endswith() #以...开头; 以...结尾;返回值Ture或者False

# startswith()和endswith()  #以...开头;  以。。。结尾
name = 'wang wen'
print(name.startswith('wa'))  #以wa开头
#True
print(name.endswith('n'))   #以n结尾

4.rsplit() 从右开始切分

#rsplit() 从右开始切分

info = 'wang;zhuang;peng;jiayi'
print(info.rsplit(';',1))  #从右开始把;用,切割。切割一个

5.join() 链接联和。用于将序列中的元素以指定的字符连接生成一个新的字符串。

#join()  join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
lis = [1,2,'19']
print(':'.join(lis))    #报错,数字不可和字符串拼接

lis = ['1','wang','19']
print(':'.join(lis))  #运行结果1:wang:19

6.replace() 替换 (变量名.replace('已有的值',‘想要改变的值’))

name = 'wang wen peng'
print(name.replace('peng','bin'))    #将peng替换为bin

7.isdigit() 判断字符串里是否为纯数字 (变量名.isdigit()) (只能判断字符串,返回值是True或False)

#isdigit() 判断字符串里是否为纯数字
salary = '111'
print(salary.isdigit())
salary = '111.1'
print(salary.isdigit())   # 有小数点,就不是纯数字。返回值是false

实际应用场景

# str之isdigit()应用场景
age = input('age: ')
if age.isdigit():
    age = int(age)

    if age < 18:
        print('小姐姐')
    else:
        print('阿姨好')
else:
    print(f'你的年龄能是这个{age}?')
age: 逗你玩?
你的年龄能是这个逗你玩??

1.3 其他操作(**) (了解)

  1. find|rfind|index|rindex|count
  2. center|ljust|rjust|zfill
  3. expandtabs
  4. captalize|swapcase|title
  5. is系列

1.find()、rfind()、index()、rindex()、count()

# str之find()、rfind()、index()、rindex()、count()
msg = 'my name is tank, tank shi sb, hha'

print(f"msg.find('tank'): {msg.find('tank')}")  # 找不到返回-1
print(f"msg.find('tank',0,3): {msg.find('tank',0,3)}")
print(f"msg.rfind('tank'): {msg.rfind('tank')}")  # 找不到返回-1
print(f"msg.index('tank'): {msg.index('tank')}")  # 找不到报错
print(f"msg.rindex('tank'): {msg.rindex('tank')}")  # 找不到报错
      

print(f"msg.count('tank'): {msg.count('tank')}")
msg.find('tank'): 11
msg.find('tank',0,3): -1
msg.rfind('tank'): 17
msg.index('tank'): 11
msg.rindex('tank'): 17
msg.count('tank'): 2

2.center()、ljust()、rjust()、zfill()

# str之center()、ljust()、rjust()、zfill()
print(f"'info nick'.center(50,'*'): {'info nick'.center(50,'*')}")
print(f"'info nick'.ljust(50,'*'): {'info nick'.ljust(50,'*')}")
print(f"'info nick'.rjust(50,'*'): {'info nick'.rjust(50,'*')}")
print(f"'info nick'.zfill(50): {'info nick'.zfill(50)}")  # 默认用0填充
'info nick'.center(50,'*'): ********************info nick*********************
'info nick'.ljust(50,'*'): info nick*****************************************
'info nick'.rjust(50,'*'): *****************************************info nick
'info nick'.zfill(50): 00000000000000000000000000000000000000000info nick

3.expandtabs()

# str之expandtabs()
print(f"a\tb\tc: %s"%('a	b	c	'))  # 默认制表符8个空格
print(f"'a\tb\tc'.expandtabs(32): %s"%('a	b	c	'.expandtabs(32)))
a	b	c: a  b   c   
'a	b	c'.expandtabs(32): a                               b                               c                               

4.captalize()、swapcase()、title()

# str之captalize()、swapcase()、title()
name = 'nick handsome sWAPCASE'

print(f"name.capitalize(): {name.capitalize()}")
print(f"name.swapcase(): {name.swapcase()}")  # 大小写互转
print(f"name.title(): {name.title()}")
name.capitalize(): Nick handsome swapcase
name.swapcase(): NICK HANDSOME Swapcase
name.title(): Nick Handsome Swapcase

5.is数字系列(只是为了告诉你,判断是否为数字时除了中文数字以后使用isdigit()即可)

  • isdecimal(): 检查字符串是否值包含十进制字符,如果是返回True,否则返回False。
  • isdigit(): 如果字符串只包含数字则返回True,否则返回False。
  • isnumeric(): 如果字符串中只包含数字字符,则返回True,否则返回False。
num = "1"  #unicode
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = "1" # 全角
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = b"1" # byte
num.isdigit()   # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'

num = "IV" # 罗马数字
num.isdigit()   # True
num.isdecimal() # False
num.isnumeric() # True

num = "四" # 汉字
num.isdigit()   # False
num.isdecimal() # False
num.isnumeric() # True

===================
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无

isdecimal()
True: Unicode数字,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)

isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)

================
import unicodedata

unicodedata.digit("2")   # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0

unicodedata.digit("2")   # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0

unicodedata.digit(b"3")   # TypeError: must be str, not bytes
unicodedata.decimal(b"3") # TypeError: must be str, not bytes
unicodedata.numeric(b"3") # TypeError: must be str, not bytes

unicodedata.digit("Ⅷ")   # ValueError: not a digit
unicodedata.decimal("Ⅷ") # ValueError: not a decimal
unicodedata.numeric("Ⅷ") # 8.0

unicodedata.digit("四")   # ValueError: not a digit
unicodedata.decimal("四") # ValueError: not a decimal
unicodedata.numeric("四") # 4.0

#"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"

6.is其他

  • isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。
  • isalpha(): 如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。
  • islower(): 如果字符串中只包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False。
  • isspace(): 如果字符串中只包含空白,则返回True,否则返回False
  • isupper(): 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False。
  • istitle(): 如果字符串是标题类型的(见title()),则返回True,否则返回False。

4.存一个值or多个值:一个值

5.有序or无序:只要是有索引的,都是有序的,因此字符串是有序的。

name = 'nick'
print(f'first:{id(name)}')
name = 'nick handsome'
print(f'second:{id(name)}')
first:4377100160
second:4377841264

6.可变or不可变:不可变数据类型

原文地址:https://www.cnblogs.com/wwbplus/p/11311403.html