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上,这时鼠标会变成 ...
随机推荐
- C# set get 函数 属性访问器
属性访问器 拿东西就是Get,放东西就是Setprivate string namepublic String Name{set{name = value;}get{return name;}}ge ...
- 日志组件一:Log4j
log4j是Apache的一个开源项目,陪伴了我们多年,但是现在已经不更新了.官网原文如下: Log4j 1.x has been widely adopted and used in many ap ...
- OpenStack云平台的网络模式及其工作机制
网络,是OpenStack的部署中最容易出问题的,也是其结构中难以理清的部分.经常收到关于OneStack部署网络方面问题和OpenStack网络结构问题的邮件.下面根据自己的理解,谈一谈OpenSt ...
- rPithon vs. rPython(转)
Similar to rPython, the rPithon package (http://rpithon.r-forge.r-project.org) allows users to execu ...
- 打开Eclipse弹出“No java virtual machine was found..."的解决方法
今天准备用Eclipse抓取Android应用崩溃log,打开Eclipse时发现运行不了有以下弹框 A Java Runtime Environment(JRE) or Java Developme ...
- 20个php框架
对于Web开发者来说,PHP是一款非常强大而又受欢迎的编程语言.世界上很多顶级的网站都是基于PHP开发的.本文我们来回顾一下20个2014年最优秀的PHP框架. 每一个开发者都知道,拥有一个强大的框架 ...
- c++概括
c++到底是什么样的语言 在过去的几十年,计算机技术的发展令人吃惊,当前的笔记本电脑的计算速度和存储信息的能力超过了20世纪60年代的大型机.20世纪七十年代,C和Pascal语言引领人们进入结构化编 ...
- NOSQL基础概念
NoSql是一个很老的概念了,但对自己来说,仍然是一个短板,果断补上. 首先通过几个简单的例子来了解NOSQL在国内的情况(2013年左右的数据,有些过时),比如新浪微博,其就有200多台物理机运行着 ...
- 【iOS】UIDynamicAnimator动画
创建动画 UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; 协议代理 ...
- Windows 7安装Oracle 10g的方法
Windows7下安装Oracle 10g提示"程序异常终止,发生未知错误"的解决方法 1.修改Oracle 10G\database\stage\prereq\db\refhos ...