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'])

 


 

 


 



 



 




 


                                                                                                                                                                                           

 






 

 


posted @ 2017-05-08 10:54  lazyball  阅读(366)  评论(0编辑  收藏  举报