首页 > 其他分享 >字符串类型内置方法

字符串类型内置方法

时间:2023-05-29 22:03:38浏览次数:35  
标签:info 内置 name nick print 类型 字符串 True msg

一、字符串类型内置方法(str)
1.用途:描述性质的东西,如人的名字、单个爱好、地址、国家等

2.定义:使用''、""、''''''、""""""包裹的的一串字符

u'unicode': unicode编码的字符串
b'101': 二进制编码的字符串
r'\n': 原生字符串,也就是说'\n'这是普通的两个字符,并没有换行的意思

name = 'nick'  # name =str('nick')
s1 = str(1.1)
s2 = str([1, 2, 3])

print(f's1:{s1}, type:{type(s1)}')
print(f's2:{s2}, type:{type(s2)}')
default
s1:1.1, type:<class 'str'>
s2:[1, 2, 3], type:<class 'str'>

3.常用操作+内置方法:常用操作和内置方法分为优先掌握(今天必须得记住)、需要掌握(一周内记住)、其他操作(了解)三个部分。

1.1 优先掌握(*****)
按索引取值
切片
长度len
成员运算in|not in
移除空白strip
切分split
循环
1.按索引取值(只可取不可改变)

# str索引取值
msg = 'hello nick'
#      0123456789  # 索引序号

print(f'索引为6: {msg[6]}')
print(f'索引为-3: {msg[-3]}')
default

索引为6: n
索引为-3: i
2.切片(顾头不顾尾,步长)

# 索引切片
msg = 'hello nick'
#      0123456789  # 索引序号

print(f'切片3-最后: {msg[3:]}')
print(f'切片3-8: {msg[3:8]}')
print(f'切片3-8,步长为2: {msg[3:8:2]}')
print(f'切片3-最后,步长为2: {msg[3::2]}')

# 了解,步长为正从左到右;步长为负从右到左
print('\n**了解知识点**')
print(f'切片所有: {msg[:]}')
print(f'反转所有: {msg[::-1]}')
print(f'切片-5--2: {msg[-5:-2:1]}')
print(f'切片-2--5: {msg[-2:-5:-1]}')
default

切片3-最后: lo nick
切片3-8: lo ni
切片3-8,步长为2: l i
切片3-最后,步长为2: l ik

了解知识点
切片所有: hello nick
反转所有: kcin olleh
切片-5--2: ni
切片-2--5: cin
3.长度len

# str长度
msg = 'hello nick'

print(len(msg))
default

10
4.成员运算in和not in

# str成员运算
msg = 'my name is nick, nick handsome'

print(f"'nick' in msg: {'nick' in msg}")
print(f"'jason' not in msg: {'jason' not in msg}")
print(f"not 'jason' in msg: {not 'jason' in msg}")
default
'nick' in msg: True
'jason' not in msg: True
not 'jason' in msg: True

5.移除空白strip()

# str移除空白strip()
name = '&&&n ick'

print(f"name.strip('&'): {name.strip('&')}")  # strip()默认为‘ ’,并且不修改原值,新创建空间
print(f"name: {name}")

# strip()应用场景
pwd = input('password: ')  # 用户可能会手抖输入空格
if pwd.strip() == '123':
    print('密码输入成功')

print(f"'*-& nick+'.strip('*-& +'): {'*-& nick+'.strip('*-& +')}")
default
name.strip('&'): n ick
name: &&&n ick
password: 123   
密码输入成功
'*-& nick+'.strip('*-& +'): nick

6.切分split

# str切分split
info = 'nick:male:19'
info_list1 = info.split(':')
info_list2 = info.split(':', 1)

print(f'info_list1:{info_list1}')
print(f'info_list2:{info_list2}')
default
info_list1:['nick', 'male', '19']
info_list2:['nick', 'male:19']

7.循环

msg = 'hello nick'

for i in msg:
    print(i)
default

h
e
l
l
o

n
i
c
k
1.2 需要掌握(****)
lstrip&rstrip
lower&upper
startswith&endswith
rsplit
join
replace
isdigit
1.lstrip()和rstrip()

# str之lstrip()和rstrip()
name = '&&nick&&'

print(f"nick.lstrip('&'): {name.lstrip('&')}")
print(f"nick.rstrip('&'): {name.rstrip('&')}")
default
nick.lstrip('&'): nick&&
nick.rstrip('&'): &&nick

2.lower()和upper()

# str之lower()和upper()
name = 'Nick Chen'

print(f"name.upper(): {name.lower()}")
print(f"name.upper(): {name.upper()}")
default
name.upper(): nick chen
name.upper(): NICK CHEN

3.startswith()和endswith()

# str之startswith()和endswith()
name = 'Nick Chen'

print(f"name.startswith('Nick'): {name.startswith('Nick')}")
print(f"name.endswith('chen'): {name.endswith('chen')}")
default
name.startswith('Nick'): True
name.endswith('chen'): False

4.rsplit()

# str之rsplit()
info = 'nick:male:19'

print(f"info.rsplit(':', 1): {info.rsplit(':', 1)}")  # 从右开始切割
default
info.rsplit(':', 1): ['nick:male', '19']

5.join()

lis = [1,2,'19']
print(f"':'.join(lis): {':'.join(lis)}")  # 报错,数字不可和字符串拼接
# str之join()
lis = ['nick', 'male', '19']

print(f"':'.join(lis): {':'.join(lis)}")
default
':'.join(lis): nick:male:19

6.replace()

# str值replace()
name = 'nick shuai'

print(f"name.replace('shuai','handsome'): {name.replace('shuai','handsome')}")
default
name.replace('shuai','handsome'): nick handsome

7.isdigit()

# str值isdigit()
salary = '111'
print(salary.isdigit())  # True

salary = '111.1'
print(salary.isdigit())  # False

default
True
False

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

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

age: 逗你玩?
你的年龄能是这个逗你玩??
1.3 其他操作(**)
find|rfind|index|rindex|count
center|ljust|rjust|zfill
expandtabs
captalize|swapcase|title
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')}")
default

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填充
default
'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\tb\tc\t'))  # 默认制表符8个空格
print(f"'a\\tb\\tc'.expandtabs(32): %s"%('a\tb\tc\t'.expandtabs(32)))
default
a\tb\tc: a	b	c	
'a\tb\tc'.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()}")
default
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)}')
default
first:4377100160
second:4377841264

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

标签:info,内置,name,nick,print,类型,字符串,True,msg
From: https://www.cnblogs.com/aidd/p/17441763.html

相关文章

  • C++ Primer 第一、二章 C++基础,变量和基本类型
    一、C++基础<iostream>包含两个基础类型,istream-输入流和ostrea-输出流。标准库定义了四个IO对象cin-标准输入(istream),cout-标准输出(o),cerr-标准错误(o),clog-用来输出程序运行时的一般性信息(o)。 #include<iostream>intmain(){std::cout<<"Enter"<<std:......
  • 数字类型内置方法
    整型1.作用整型(int)通常用于表示身高、体重、年龄和ID号等整数值。2.定义方式在Python中,可以使用标准整数表示法来定义一个整型变量。例如:pythonage=183.方法整型数据类型在Python中有许多内置方法可供使用,下面是一些常见的整型内置方法:bit_length():返回整数的二......
  • 【python基础】基本数据类型-数字类型
    Python3支持int(整型数据)、float(浮点型数据)、bool(布尔类型)1.int(整型数据)在Python3里,只有一种整数类型int,表示为长整型。像大多数语言一样,数值类型的赋值和计算都是很直观的。1.1数值运算编写程序如下所示运行结果如下所示这里需要注意的是数值的除法运算,包含两......
  • v-if 判断是否包含字符串
    <el-buttonv-if="!table.name.includes('模板')"type="danger"size="mini"@click="deleteTempalte(table)">删除</el-button> <trv-for="(subsidy,i......
  • 批量删除/修改文件名中的某些字符串
    问题解决1.首先要批处理文件(夹),放在同一文件目录下。如:2.在该目录下,新建文本文件,输入以下代码,如:set/pstr1=请输入要替换的文件(文件夹)名字符串(可替换空格):set/pstr2=请输入替换后的文件(文件夹)名字符串(若删除直接回车):for/f"delims="%%ain('dir/s/b^|sort/......
  • 5-28 字符串杂题
    训练一共布置了8题,其中除了H以外,剩下的题目都是字符串题。这些题全部都可以只用哈希做,也全部都可以不用哈希做。CF126B-Password题意:要求找到一个字符串同时是\(S\)的前缀、后缀、非前后缀子串。哈希做法:首先,我们要查找,需要多短的前缀才能保证其有过非前后缀子串的出现......
  • Java中如何获得A<T>泛型中T的运行时类型及原理探究(转)
    原文:https://developer.aliyun.com/article/1226646简介如果经常写工具类,很大概率会遇到一个比较实际的问题,就是需要在泛型表达式A中获取T的运行时类型。获取它需要一些技巧。但这个技巧很少被透彻的解释过为什么会生效。在接下来的文章里,我们会从Java的泛型(Generics)谈起,结合JLS......
  • GO数据类型(二)--字符串
    (文章目录)转义字符每一个都是一个字符,rune类型(int32)。可以作为单独字符使用,也可以作为字符串中的一个字符。\aU+0007alertorbell\bU+0008backspace\fU+000Cformfeed\nU+000Alinefeedornewline\rU+000Dcarriagereturn\tU+0009horizontal......
  • Problem L: STL——字符串排序
    HomeWebBoardProblemSetStandingStatusStatisticsProblemL:STL——字符串排序TimeLimit:1Sec  MemoryLimit:128MBSubmit:3482  Solved:1666[Submit][Status][WebBoard]Description  对N个字符串排序。  0<N<=5000......
  • 字符串匹配|kmp笔记
    很久之前学的了。做个笔记回忆一下:kmp朴素比对字符串所谓字符串匹配,是这样一种问题:“字符串T是否为字符串S的子串?如果是,它出现在S的哪些位置?”其中S称为主串;T称为模式串。如在字符串sabcabcabcabd中找到子串Tabcabd:先设两个指针i、j,i表示S的指针,j表示T的指针......