str-字符串功能介绍
叨逼叨:字符串的各个功能修改不是本身,本身不变,会产生新的值,需要赋值给新的变量来接收
以下 ”举例“ 是解释每个功能的实例 “举例”下一行是pycharm里原本的英文解释,对比着看看,对以后直接看英文有帮助吧,毕竟以后还是要依靠pycharm,而不是都记住。
#创建
#a = ‘alex’
#a = str(‘alex’)
#转换
#Age = 18
# Age = str(‘age’)
#1.首字母大写
name = 'alex'
v = name.capitalize()
print(name)
print(v)
#执行结果:
alex
Alex
#可以看到原值并没有改变
举例
def capitalize(self): # real signature unknown; restored from __doc__
"""
S.capitalize() -> str Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
"""
return ""
capitalize
#2.大写变小写
name = 'ALex'
v = name.casefold() #包括所有语言,比较厉害
v2 = name.lower() # 仅仅针对英文
print(v2)
print(v)
举例
def casefold(self): # real signature unknown; restored from __doc__
"""
S.casefold() -> str Return a version of S suitable for caseless comparisons.
"""
return ""
casefold
def lower(self): # real signature unknown; restored from __doc__
"""
S.lower() -> str Return a copy of the string S converted to lowercase.
"""
return ""
lower
#3.小写变大写
name = 'alex'
v = name.upper()
print(v)
举例
def upper(self): # real signature unknown; restored from __doc__
"""
S.upper() -> str Return a copy of S converted to uppercase.
"""
return ""
upper
#4.判断是否是大小写
name = 'ALX'
v1 = name.islower()#判断是否是小写
v2 = name.isupper()#判断是否是大写
print(v2)
print(v1)
举例
def islower(self): # real signature unknown; restored from __doc__
"""
S.islower() -> bool Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
return False
islower
def isupper(self): # real signature unknown; restored from __doc__
"""
S.isupper() -> bool Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False
isupper
#5.居中 填充 总长度
#参数1:包括alex在内的总长度 必选
#参数2:填充的字符串 可选参数
# name = 'alex'
# v0 = name.center(20)
# v = name.center(20,'*')
# print(v0)
# print(v)
# 执行结果
# alex
# ********alex********
举例
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return ""
center
#6.左右填充
#参数1:左/右空白加alex的总长度 必选
#参数2:填充物 可选
# name = 'alex'
# v = name.ljust(20,'*') #有个小规律 l代表left 自然是左填充
# v1 = name.rjust(20)# r right 右填充
# print(v1)
# print(v)
# #执行结果
# alex
# alex**************** # 以0右填充
# name = 'alex'
# v = name.zfill(20)
# print(v)
#执行结果:
#0000000000000000alex
举例
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
"""
return ""
ljust
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return ""
rjust
#7.统计子序列(或规定范围)出现的次数
#子序列:儿子,变量的值的部分
#参数1:子序列
#参数2:范围,区间 >=前边的 <后边的 基本涉及区间的都是这个规律
# name = 'alexaaa'
# v = name.count('a')
# v1 = name.count('a',4,7)
# print(v1)
# print(v)
举例
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return 0
count
#8.#判断开始或结束的子序列
# name = 'alex'
# v = name.endswith('x') #判断是否以 x 结尾
# v1 = name.startswith('a') #判断是否以 a 开头
# print(v)
# print(v1)
举例
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
"""
return False
endswith
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False
startswith
#9.针对制表符(空格),像是在做表格
# name = 'alex\teric\tseven\nqiqi\taman\tyangzai'
# v = name.expandtabs(20)
# print(v)
#执行结果
# alex eric seven
# qiqi aman yangzai
举例
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
return ""
expandtabs
#10.根据子序列,打印索引位置
#参数1:子序列
#参数2:区间
name = 'alex'
v = name.find('a')
v1 = name.find('a',1,3) #find 没有找到的话,显示-1不报错
v2 = name.index('a',1,3) #index 没有找到的话,报错
print(v)
print(v1)
print(v2)
举例
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0
find
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found.
"""
return 0
index
#11.字符串格式化
##最开始学的字符串格式化 和今天学习的对比
# name = 'alex'
# age = 23
# user_info = '我叫%s,今年%s 岁' %(name,age)
# print(user_info)
##format有两种方式
###第一种方式
# user_info = '我叫{0},今年{1}'
# v = user_info.format('alex',23)
# print(v)
###第二种方式
# user_info = '我叫{name},今年{age}'
# v = user_info.format(name = 'alex',age = 23)
# print(v)
##format_map 传值是字典形式
# user_info = '我叫{name},今年{age}'
# v = user_info.format_map({'name':'alex','age':23})
# print(v)
举例
def format(self, *args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass
format
def format_map(self, mapping): # real signature unknown; restored from __doc__
"""
S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
"""
return ""
format_map
#12. 是否是标识符
#只针对数字,字母,下划线判断,不能以数字开头,无法判断是否使用python内置变量名字
# n = 'name'
# v = n.isidentifier()
# print(v)
举例
def isidentifier(self): # real signature unknown; restored from __doc__
"""
S.isidentifier() -> bool Return True if S is a valid identifier according
to the language definition. Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
"""
return False
isidentifier
#13.是否包含隐含的字符
# name = 'ale\tx\n'
# v = name.isprintable()
# print(v)
举例
def isprintable(self): # real signature unknown; restored from __doc__
"""
S.isprintable() -> bool Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
"""
return False
isprintable
#14.是否有空格,是有空格,不是是否为空
# name = ' '
# v = name.isspace()
# print(v)
举例
def isspace(self): # real signature unknown; restored from __doc__
"""
S.isspace() -> bool Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
"""
return False
isspace
#15.判断是否是标题,就是判断首字母是否大写
# name = 'Alex'
# v = name.istitle()
# print(v)
举例
def istitle(self): # real signature unknown; restored from __doc__
"""
S.istitle() -> bool Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
"""
return False
istitle
#16.对应替换
# m = str.maketrans('abcd','1234') #对应关系 abcd 对应 1234 那就是 a对应1 b对应2 以此类推
# name = 'adfjdfbldfkdkckjkdjfd'
# v = name.translate(m)
# print(v)
#执行结果
#14fj4f2l4fk4k3kjk4jf4 对应着分别替换了
举例
def maketrans(self, *args, **kwargs): # real signature unknown
"""
Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
"""
pass
maketrans
def translate(self, table): # real signature unknown; restored from __doc__
"""
S.translate(table) -> str Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
"""
return ""
translate
#17. 替换
#参数1:旧的内容
#参数2:新的内容
#参数3:替换几个,默认都替换
# name = 'alexericsevenalex'
# v = name.replace('alex','ALEX')
# v1 = name.replace('alex','ALEX',1)
# print(v1)
# print(v)
举例
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
"""
S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return ""
replace
#18.移除空白
# name = 'alex \t\n'
# v = name.strip()
# print(v)
# print(name.strip()) # 左右
# print(name.rstrip()) # 右
# print(name.lstrip()) # 左
举例
def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> str Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
strip
#19. 大小写转换
name = 'ALex'
v =name.swapcase()
print(v)
举例
def swapcase(self): # real signature unknown; restored from __doc__
"""
S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase
and vice versa.
"""
return ""
swapcase
#20. 分割
# name = 'alexbclexbfelx'
# v = name.split('b') # 以b分
# v0 = name.split('b',1) #
# v1 = name.partition('b')
# print(v)
# print(v0)
# print(v1)
#执行结果
#['alex', 'clex', 'felx']
#['alex', 'clexbfelx']
#('alex', 'b', 'clexbfelx')
举例
def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
return []
split
def partition(self, sep): # real signature unknown; restored from __doc__
"""
S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass
partition
#21.元素拼接(元素字符串)
# name = 'alex'
# v1 = '|'.join(
# print(v1)
# #执行结果
# #a|l|e|x
# name_list = ['
# v = "搞".join(n
# print(v)#分割
# #执行结果
# #海峰搞杠娘搞李杰搞李泉
举例
def join(self, iterable): # real signature unknown; restored from __doc__
"""
S.join(iterable) -> str Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return ""
join
#22. **** 转换成字节 ****
# name = "李杰"
# v1 = name.encode(e
# print(v1)
# v2 = name.encode(e
# print(v2)
#打印结果
#b'\xe6\x9d\x8e\xe6\
#b'\xc0\xee\xbd\xdc'
举例
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
"""
S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
"""
return b""
encode
# 23. 判断是否是数字
# num = '②'
# v1 = num.isdecima
# v2 = num.isdigit(
# v3 = num.isnumeri
# print(v1,v2,v3)
举例
def isdecimal(self): # real signature unknown; restored from __doc__
"""
S.isdecimal() -> bool Return True if there are only decimal characters in S,
False otherwise.
"""
return False
isdecimal
def isdigit(self): # real signature unknown; restored from __doc__
"""
S.isdigit() -> bool Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
return False
isdigit
def isnumeric(self): # real signature unknown; restored from __doc__
"""
S.isnumeric() -> bool Return True if there are only numeric characters in S,
False otherwise.
"""
return False
isnumeric
# 24. 是否是数字、汉字.
比较懵
# name = 'alex8汉子'
# v = name.isalnum() # 字,数字
# print(v) # True
# v2 = name.isalpha()#
# print(v2)# False
举例
def isalnum(self): # real signature unknown; restored from __doc__
"""
S.isalnum() -> bool Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
return False
isalnum
def isalpha(self): # real signature unknown; restored from __doc__
"""
S.isalpha() -> bool Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
return False
isalpha
#25.字符串格式化
%s 字符串 传入的值都自动转为字符串
%d 数字 必须传入数字,否则报错
%f 浮点数
%r raw string 原生字符 非转义 输入啥就输出啥
msg = "my name is %s and age is %f" % ("alex",23) ##原来后边不仅仅可以写变量,还可以直接写值呢,字符串记得“”
print(msg)
name = "alex"
age = 18
msg = "My name is %s ,and my age is %s" % (name,age)
print(msg)
举例
#26.字符串拼接
name = "alex" gender = '女' name_gender = name + gender print(name_gender)
举例
#27.长度
user_info = "alex sb123 9" print(len(user_info))
举例
#28.索引
user_info = "alex sb123 9"
print(user_info[0])
举例
#29.切片
name = 'alex zhenni' print(name[0]) print(name[-1]) print(name[0:-1]) print(name[:-1]) print(name[2:5]) print(name[0:-1:2]) #步长
举例
常用的也是比较重要的
# name = 'alex'
# name.upper()
# name.lower()
# name.split()
# name.find()
# name.strip()
# name.startswith()
# name.format()
# name.replace()
# "alex".join(["aa",'bb'])
str-字符串功能介绍的更多相关文章
- Python中str字符串的功能介绍
Str字符串的功能介绍 1. 字符串的操作 字符串的连接操作 符号: + 格式:str1 + str2 例如:str1 = 'I Love' str2 = 'You!' print(str1 + st ...
- Python——str(字符串)内部功能介绍
str内部功能详解: class str(object): """ str(object='') -> str str(bytes_or_buffer[, enco ...
- C#构造方法(函数) C#方法重载 C#字段和属性 MUI实现上拉加载和下拉刷新 SVN常用功能介绍(二) SVN常用功能介绍(一) ASP.NET常用内置对象之——Server sql server——子查询 C#接口 字符串的本质 AJAX原生JavaScript写法
C#构造方法(函数) 一.概括 1.通常创建一个对象的方法如图: 通过 Student tom = new Student(); 创建tom对象,这种创建实例的形式被称为构造方法. 简述:用来初 ...
- Python中模块之re的功能介绍
re模块的功能介绍 1. 方法 match 从开头开始查找 方法:re.match(pattern,string,flags=0) 返回值:<class '_sre.SRE_Match'> ...
- Python中模块之shutil及zipfile&tarfile的功能介绍
shutil的功能介绍及其他打包.压缩模块 1. shutil模块的方法 chown 更改指定路径的属组 2. copy 拷贝文件和权限 方法:shutil.copy(src,dst,*,follow ...
- Python中模块之sys的功能介绍
sys模块的功能介绍 1. sys的变量 argv 命令行参数 方法:sys.argv 返回值:list 例如:test1.py文件中有两句语句1.import sys 2.print(sys.arg ...
- Python中模块之os的功能介绍
Python中模块之os的功能介绍 1. os的变量 path 模块路径 方法:os.path 返回值:module 例如:print(os.path) >>> <module ...
- Python中模块之time&datetime的功能介绍
time&datetime的功能介绍 1. time模块 1. 时间的分类 1. 时间戳:以秒为单位的整数 2. 时间字符格式化:常见的年月日时分秒 3. 时间元祖格式:9大元素,每个元素对应 ...
- Python中模块之copy的功能介绍
模块之copy的功能介绍 copy主要分两种: 1.浅拷贝 2.深拷贝 赋值: 在python中赋值算特殊的拷贝,其实赋值可以理解为同一个对象有两个名字,所以当其中一个发生变化,另一个也跟着会变化. ...
- Python小白学习之路(三)—【数字功能】【字符串功能】
数字(int)常见功能 在网络课上,老师把这些功能称为神奇的魔法,想要揭开魔法神奇的面纱,想要看看有什么招数,在Pycharm里敲击三个字母(int),按住Ctrl,将鼠标点在int上,这时鼠标会变成 ...
随机推荐
- Python可视化:Seaborn库热力图使用进阶
前言 在日常工作中,经常可以见到各种各种精美的热力图,热力图的应用非常广泛,下面一起来学习下Python的Seaborn库中热力图(heatmap)如何来进行使用. 本次运行的环境为: windows ...
- 那些日常琐事(iPhone上的细小提示,大数据分析)
今天早上蹲坑玩手机的时候,无意间看到了iPhone 给我一些提醒,震惊了我.也许你们会说,没什么大惊小怪的,当然做程序的都知道苹果公司早就记载了我们日常生活中很多数据,只是苹果公司目前还没做 ...
- Coursera 机器学习笔记(八)
主要为第十周内容:大规模机器学习.案例.总结 (一)随机梯度下降法 如果有一个大规模的训练集,普通的批量梯度下降法需要计算整个训练集的误差的平方和,如果学习方法需要迭代20次,这已经是非常大的计算代价 ...
- PHP基础入门(三)---PHP函数基础
PHP基础入门(三)---函数 今天来给大家分享一下PHP的函数基础.有了前两章的了解,想必大家对PHP有了一定的基础了解.想回顾前两章的朋友可以点击"PHP基础入门(一)"&qu ...
- MVC分层含义与开发方式
真正的服务层是面向数据的,假想一切数据都是从参数获得 控制层是接受页面层数据,再传给服务层,然后将结果返回给页面层的(客户) 页面层是提交格式化的数据的(容易小混乱,无格式,所以要格式化,可以在中间加 ...
- 【webpack整理】一、安装、配置、按需加载
如果你: 是前端热爱者 :) 有JavaScript/nodejs基础 会使用一些常用命令行,mkdir,cd,etc. 会使用npm 想对webpack有更深的认识,或许此时你恰好遇到关于webpa ...
- String 类问题发现与解决
1.在代码中出现:String t = null; t.length(); 执行后:控制台报:java.lang.NullPointerException 原因:Java中,null是一个关键字,用来 ...
- navicat连接oracle 报 ORA-12737 set CHS16GBK
1首先,我们打开“工具”-->"选项"菜单,见到如下界面,依据OCI library(oci.dll) 路径,导航到 navicat oci 目录下,备份里面的文件(通过在该 ...
- Cordova各个插件使用介绍系列(一)—$cordovaSms发送短信
详情链接地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/cordova-1-cordovasms/ 这是调用手机发送短信的插件 ...
- css透明度的设置
Css代码 .transparent_class { filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: ...