Python之字符串详解1

1. 查看类型
name = ‘allen‘
print(type(name))     #查看类型
<class ‘str‘>         #类型为str

age = 19
print(type(name))     #查看类型
<class ‘int‘>         #类型为int

 2. center

描述:居中显示

语法:

    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        B.center(width[, fillchar]) -> copy of B

        Return B centered in a string of length width.  Padding is
        done using the specified fill character (default is a space).
        """
        pass

样例:

name = ‘allen‘
result=name.center(20,‘*‘)   #居中对齐,显示20个字符,默认以*号代替
print(result)

*******allen********  #显示结果

center

3. ljust

描述:左对齐显示

语法:

    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 ""

样例:

name = ‘allen‘
result=name.ljust(20,‘*‘)    #左对齐,显示20个字符,默认以*号代替
print(result)

allen***************    #显示结果

ljust

 4. rjust

描述:右对齐显示

语法:

    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 ""

样例:

name = ‘allen‘
result=name.rjust(20,‘*‘)    #居右对齐,显示20个字符,默认以*号代替
print(result)

***************allen    #显示结果

rjust

5. capitalize/title

描述:首字母大写

语法:

   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 ""

样例:

name = ‘allen‘
result=name.capitalize()    #首字母转换为大写,其他小写
print(result)

Allen    #结果显示

name = ‘allen‘
result=name.title()    #首字母转换为大写,其他小写
print(result)

Allen    #结果显示

capitalize

6. lower

描写:所有字符转换为小写

语法:

  def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""

样例:

name = ‘ALLEN‘
result=name.lower()    #所有字符转换为小写
print(result)

allen    #结果显示

lower

7. upper

描写:所有字符转换为大写

语法:

 def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""

样例:

name = ‘allen‘
result=name.upper()    #所有字符转换为大写
print(result)

ALLEN    #结果显示

upper

8. encode

描写:编码转换

语法:

 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""

样例:

name = ‘你好‘
print(name)
a = name.encode(‘gbk‘)  #编码转换utf8->uncode->gbk
print (a)

你好        #utf-8编码显示结果
b‘\xc4\xe3\xba\xc3‘    #gbk编码显示结果

encode

9. startswith

描写:判断以什么字符开头,结果范围True or False

语法:

   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

样例:

name = ‘allen‘
a = name.startswith(‘a‘)    #判断字符串以a开头
print(a)

True    #显示结果

name = ‘allen‘
a = name.startswith(‘a‘,0,4)      #判断‘allen’是否以a开头
print(a)

True    #显示结果

startswith

10. endswith

描写:判断以什么字符结尾,结果范围True or False,需注意取值与startswith略有不同

语法:

    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

样例:

name = ‘allen‘
a = name.endswith(‘n‘,1,5)    #判断‘allen’是否以n结尾
print(a)

True    #结果显示

endswith

11. expandtabs

描写:将tab转换成8个空格

语法:

    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 "

样例:

name = ‘a\tllen‘
result=name.expandtabs()  #将1个tab转换成8个空格
print(result)

a       llen    #显示结果

expandtabs

12. find

描写:查找序列,返回所在的位置下标。若没有找到,结果返回值为-1

语法:

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

样例:

name = ‘allen‘
result = name.find(‘e‘)    #查找字符是否包含e
print(result)

3    #结果显示,找到e并返回所在下标值

name = ‘allen‘
result = name.find(‘x‘)    #查找字符是否包含x
print(result)

-1   #结果显示为找到,返回值为-1

find

13. index

描写:查找序列,返回所在的位置下标。若没有找到,结果为报错

语法:

    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

样例:

name = ‘allen‘
result = name.index(‘aa‘) #查找字符中是否包含aa
print(result)

NameError: name ‘name‘ is not defined    #未找到,结果显示报错信息

index

14. count

描写:搜索关键字并计数

语法:

  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

样例:

name = ‘aasd;asdfasdfas‘
a = name.count(‘df‘)    #搜索‘df’的个数
print(a)

2    #显示结果

name = ‘aasd;asdfasdfas‘
a = name.count(‘df‘,0,10)  #在0-10下标内,所搜‘df’的个数
print(a)

1    #显示结果

count

15. format

描写:字段拼接,类似于%s

语法:

  def format(*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

样例:

name = "aa {name} {id}"
result = name.format(name=‘allen‘,id=‘123‘)    #变量赋值,拼接内容
print(result)

aa allen 123    #显示结果

format

16. replace

描写:字符替换

语法:

 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 ""

样例:

name = ‘allen‘
result=name.replace(‘a‘,‘e‘)    #将字符a更改为e
print(result)

ellen    #显示结果

name = ‘allen‘
result=name.replace(‘l‘,‘o‘,1)    #将字符l替换成o,限第一次匹配
print(result)

aolen    #显示结果

replace

17. partition

描写:搜索关键字,以关键字为分隔符。若未匹配,则显示为空的字符串

语法:

    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

样例:

name = ‘allenisboy‘
result=name.partition(‘is‘)    #以is为分隔符
print(result)

(‘allen‘, ‘is‘, ‘boy‘)    #显示结果

partition

18 join

描写:以定义的字符为分隔符,进行内容拼接

语法:

    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 ""

样例:

list = [‘a‘,‘b‘,‘c‘,‘d‘]
result="_".join(list)    #以下滑线为分隔符,进行拼接
print(result)

a_b_c_d    #结果显示

join

19. split

描写:以定义的字符为分隔符,进行字符串分割

语法:

    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 []

样例:

name =‘‘‘
aaa
bbb
ccc‘‘‘

result=name.split(‘\n‘)    #以换行为分隔符,进行分割
print(result)

[‘‘, ‘aaa‘, ‘bbb‘, ‘ccc‘]    #结果以列表形式显示

split

20. splitlines

描写:以换行符为分隔符,进行字符串分割

语法:

 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

样例:

name =‘‘‘
aaa
bbb
ccc‘‘‘
result=name.splitlines()    #默认以换行符进行分割
print(result)

[‘‘, ‘aaa‘, ‘bbb‘, ‘ccc‘]    #以列表项是显示结果

splitlines

21. strip

描写:移除字符串头尾指定的字符(默认为空格)。

语法:

    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 ""

样例:

name = ‘123allen‘
result=name.strip(‘12‘)    #移除包含1、2的字符
print(result)

3allen    #显示结果

result=name.strip(‘21‘)    #移除包含1、2的字符
print(result)

3allen    #显示结果

strip

21. lstrip

描写:左匹配字符串,进行移除操作

语法:

    def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

样例:

name = ‘123allen‘
result=name.lstrip(‘213‘)    #从左开始,搜索字符1,2,3并移除
print(result)

allen    #显示结果

lstrip

22. rstrip

描写:右匹配字符串,进行移除操作

语法:

    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str

        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

样例:

name = ‘123allen‘
result=name.rstrip(‘en‘)    #从右边开始,搜索en并移除
print(result)

123all    #显示结果

rstrip

 

时间: 2024-10-29 19:10:53

Python之字符串详解1的相关文章

一起学python 三 --字符串详解,for循环

1.整型 n = 56 print(n.bit_length()) #查看值用几位(bit) # python2 中有长整型 long # python3 中全都是整型 2.bool True False print(boll(num)) #非0数字输出Ture 数字0输出False 所有空的都是False 0,None,[],{},(),"" print(int(True)) 1 print(int( False)) 0 ## 字符串转布尔值的时候,只要不为空就是Ture3.字符串详

python的字符串详解

python的字符串内建函数详解: 一.string.capitalize() 描述: string.capitalize():将字符串的第一个字母变成大写,其他字母变小写.对于 8 位字节编码需要根据本地环境. 语法:          name = 'luwenjuan'          name.capitalize() 无参数 二.string.decode(encoding='UTF-8', errors='strict') 描述: string.decode(encoding='U

Python字符编码详解(转)

1. 字符编码简介 1.1. ASCII ASCII(American Standard Code for Information Interchange),是一种单字节的编码.计算机世界里一开始只有英文,而单字节可以表示256个不同的字符,可以表示所有的英文字符和许多的控制符号.不过ASCII只用到了其中的一半(\x80以下),这也是MBCS得以实现的基础. 1.2. MBCS 然而计算机世界里很快就有了其他语言,单字节的ASCII已无法满足需求.后来每个语言就制定了一套自己的编码,由于单字节

Python之print详解

Python之print详解 http://www.jb51.net/article/55768.htm print的一些基本用法,在前面的讲述中也涉及一些,本讲是在复习的基础上,尽量再多点内容. eval() 在print干事情之前,先看看这个东东.不是没有用,因为说不定某些时候要用到. 复制代码 代码如下: >>> help(eval)      #这个是一招鲜,凡是不理解怎么用,就用这个看文档 Help on built-in function eval in module __b

【python进阶】详解元类及其应用2

前言 在上一篇文章[python进阶]详解元类及其应用1中,我们提到了关于元类的一些前置知识,介绍了类对象,动态创建类,使用type创建类,这一节我们将继续接着上文来讲~~~ 5.使?type创建带有?法的类 最终你会希望为你的类增加?法.只需要定义?个有着恰当签名的函数并将 其作为属性赋值就可以了.添加实例?法 In [14]: def echo_bar(self):#定义了一个普通的函数 ...: print(self.bar) ...: In [15]: FooChild = type('

使用Python操作Redis详解

之前的五天,过了个愉快的周末,然后将公司AbaseDump的调度部分代码看懂并且在此之上完成了OnlyDump的功能代码,代码不可以公开,今天完工,明天测试,晚上来总结一下这几天学到的一点应用. 使用Python操作Redis详解 ------------------------------------------------------------------------------------------------- 一. 文档说明 本文档仅介绍Redis在Python中的使用,Redis

整型以及布尔值的转换 字符串详解

整型以及布尔值转换 整型 -- 数字 (int) 整型(数字)用于比较和运算 计算机支持的数字范围 32位 ---2 ** 31 -1 ~ 2 ** 31 -1 64位 ---2 ** 63 -1 ~ 2 ** 63 -1 Python2和Python3在整型中的区别 python2 整型 int -- long(长整型) /获取的是整数 python3 整型 int / 获取的是浮点数(小数) 二进制和十进制 456 ----- 十进制数 0101 ----- 二进制数 除此之外还有: 十六进

整型和布尔类型的转换 &amp; 字符串详解 &amp; for循环

整型以及布尔值转换 整型 整型----数字(int)用于比较和运算 32位: -2 ** 31 - 2** 31-1 64位:-2 ** 63 - 2** 63-1 + - * / // ** % 十进制,二进制,十六进制,八进制,二进制 十进制表示方法:123456 二进制表示方法:0101 十进制--二进制(从下往上?2) 15 1 7 1 3 1 1 1 #################### 188 0 94 0 47 1 23 1 11 1 5 1 2 0 1 1 # 从下往上计算

python之struct详解

python之struct详解 2018-05-23 18:20:29 醉小义 阅读数 20115更多 分类专栏: python 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/qq_30638831/article/details/80421019 用处 按照指定格式将Python数据转换为字符串,该字符串为字节流,如网络传输时,不能传输int,此时先将int转化为字节流,然后再发送;