Python之String

字符串是Python中最常见的类型,通过在引号之间包含字符的方式来创建。

字符串类型是不可变的。

一、字符串的创建

创建与赋值

>>> FirstString = ‘Hello World!‘
>>> print(FirstString)
Hello World!

访问字符串的值

>>> FirstString[0]
‘H‘

改变一个字符串

>>> FirstString = FirstString[:6] + ‘Python‘
>>> FirstString
‘Hello Python‘

二、字符串操作

a.标准类型操作符

>>> str1 = ‘abc‘
>>> str2 = ‘opq‘
>>> str3 = ‘xyz‘
>>> str1 < str2
True
>>> str2 != str3
True
>>> str1 < str3 and str2 == ‘xyz‘
False

b.序列操作符

索引

  • 正向索引
  • 反向索引

0   1   2   3

a   b   c   d

-4  -3 -2  -1

切片

使用一个数值范围(:)作为切片操作的参数可以返回一串连续的字符。

[start:end],我们可以访问到包括start在内到end(不包括end)的所有字符,即start<=x<end。

>>> FirstString[0:5]
‘Hello‘

三、格式化操作符(%)

通过使用%来实现操作符的格式化。

>>> ‘My computer name is: %s‘ % ‘Jef‘
‘My computer name is: Jef‘

四、内建函数

   def capitalize(self):
   #S.capitalize() -> str
   #把字符串的第一个字符大写

   def casefold(self):
   #S.casefold() -> str
   #将字符串中所有大学字母改为小写
   >>> name = ‘AbCd‘
   >>> name.casefold()
   ‘abcd‘

   def center(self, width, fillchar=None):
   #将一个字符串居中,并使用填充空格至长度width的新字符串
   >>> name = ‘Jef‘
   >>> name.center(20,‘*‘)
   ‘********Jef*********‘

   def count(self, sub, start=None, end=None):
   #返回str在string里面出现的次数,可指定start与end的位置
   >>> name = ‘Jeffrey‘
   >>> name.count(‘ef‘,0,6)
   1

   def encode(self, encoding=‘utf-8‘, errors=‘strict‘):
   #encoding指定的编码格式解码string
   >>>name.encode(‘gbk’) 

   def endswith(self, suffix, start=None, end=None):
   #检查是否以某个字符结束,可指定start与end范围 

   def expandtabs(self, tabsize=8):
   #把tabs转换为空格,默认一个tab转换为8个空格
        """
   def find:
   #检测sub是否在字符串中
   >>> name = ‘Jeffrey‘
   >>> name.find(‘ef‘,0,5)
   1

    def format(*args, **kwargs):
    #字符串格式化
    >>> name = ‘Python is {0}‘
    >>> name = name.format(‘No.1‘)
    >>> print(name)
    Python is No.1

    def format_map(self, mapping):
        S.format_map(mapping) -> str 

    def index(self, sub, start=None, end=None):
    #与find方法一直,区别在于index会返回一个异常
        """
    def isalnum(self):
    #判断字符串中至少有一个字符并且所有字符都是字母或数字则返
       回True,否则返回False

    def isalpha(self):
    #判断字符串中至少有一个字符并且所有字符都是字母则返回True,
       否则返回False

    def isdecimal(self):
    #判断字符串只包含十进制数字则返回True 否则返回False

    def isdigit(self):
    #判断字符串中只包含数字则返回True 否则返回False

    def isidentifier(self):
    #判断字符串是否是合法的标识符

    def islower(self):
    #判断字符串中都是小写字母

    def isnumeric(self):
    #判断字符串中只包含数字字符,则返回True,否则返回False

    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 

    def isspace(self): #
    #判断字符串中是否只包含空格

    def istitle(self):
    #判断字符串是标题化的(见title())则返回True,否则返回False

    def isupper(self):
    #判断字符串中都是大写字母

    def join(self, iterable):
    #合并一个新的字符串
    >>> li = [‘J‘,‘e‘,‘f‘]
    >>> result = "".join(li)
    >>> print(result)
    Jef

    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
    #返回一个原字符串左对齐,并使用空格填充至长度width 的新字符串

    def lower(self):
    #转换字符串中所有大写字符为小写

    def lstrip(self, chars=None):
    #截掉string 左边的空格

    def maketrans(self, *args, **kwargs): # real signature unknown 

    def partition(self, sep):
    #将字符串进行分割
    >>> name = ‘jefissmart‘
    >>> result = name.partition(‘is‘)
    >>> print(result)
    (‘jef‘, ‘is‘, ‘smart‘)

    def replace(self, old, new, count=None):
    #将字符串中的old 替换成new,可指定次数   

    def rfind(self, sub, start=None, end=None):
    #类似于find()函数,不过是从右边开始查找

    def rindex(self, sub, start=None, end=None):
    #类似于index(),不过是从右边开始

    def rjust(self, width, fillchar=None):
    #返回一个原字符串右对齐,并使用空格填充至长度width 的新字符串

    def rpartition(self, sep):
    #

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings 

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
       """
        return [] 

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

    def split(self, sep=None, maxsplit=-1):
    #返回一个以sep分隔的列表,maxsplit指定拆分次数

    def splitlines(self, keepends=None):
    #按照行分隔,返回一个包含各行作为元素的列表

    def startswith(self, prefix, start=None, end=None):
    #检查字符串是否是以某个obj 开头

    def strip(self, chars=None):
    #在字符串上执行lstrip()和rstrip()

    def swapcase(self):
    #翻转string 中的大小写
    def title(self):
    #返回"标题化"的string,就是说所有单词都是以大写开始,其余字母均为      小写

    def translate(self, table):
    #根据str 给出的表(包含256 个字符)转换string 的字符

    def upper(self):
    #转换string 中的小写字母为大写
    >>> name = ‘Jef Is Smart‘
    >>> result = name.upper()
    >>> print(result)
    JEF IS SMART

    def zfill(self, width):
    #返回长度为width 的字符串,原字符串string 右对齐,前面填充0

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value."""
        pass 

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self."""
        pass 

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value."""
        pass 

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

        Return a formatted version of S as described by format_spec.
       """
        return "" 

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name)."""
        pass 

    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]."""
        pass 

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass 

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value."""
        pass 

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value."""
        pass 

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self)."""
        pass 

    def __init__(self, value=‘‘, encoding=None, errors=‘strict‘): # known special case of str.__init__
        """
        str(object=‘‘) -> str
        str(bytes_or_buffer[, encoding[, errors]]) -> str 

        Create a new string object from the given object. If encoding or
        errors is specified, then the object must expose a data buffer
        that will be decoded using the given encoding and error handler.
        Otherwise, returns the result of object.__str__() (if defined)
        or repr(object).
        encoding defaults to sys.getdefaultencoding().
        errors defaults to ‘strict‘.
        # (copied from class doc)
       """
        pass 

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self)."""
        pass 

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self)."""
        pass 

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value."""
        pass 

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value."""
        pass 

    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value."""
        pass 

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n"""
        pass 

    @staticmethod# known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature."""
        pass 

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value."""
        pass 

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self)."""
        pass 

    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self."""
        pass 

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value."""
        pass 

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes"""
        pass 

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self)."""
        pass 

class super(object):
   """
    super() -> same as super(__class__, <first argument>)
    super(type) -> unbound super object
    super(type, obj) -> bound super object; requires isinstance(obj, type)
    super(type, type2) -> bound super object; requires issubclass(type2, type)
    Typical use to call a cooperative superclass method:
    class C(B):
        def meth(self, arg):
            super().meth(arg)
    This works for class methods too:
    class C(B):
        @classmethod
        def cmeth(cls, arg):
            super().cmeth(arg)
   """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name)."""
        pass 

    def __get__(self, *args, **kwargs): # real signature unknown
        """ Return an attribute of instance, which is of type owner."""
        pass 

    def __init__(self, type1=None, type2=None): # known special case of super.__init__
        """
        super() -> same as super(__class__, <first argument>)
        super(type) -> unbound super object
        super(type, obj) -> bound super object; requires isinstance(obj, type)
        super(type, type2) -> bound super object; requires issubclass(type2, type)
        Typical use to call a cooperative superclass method:
        class C(B):
            def meth(self, arg):
                super().meth(arg)
        This works for class methods too:
        class C(B):
            @classmethod
            def cmeth(cls, arg):
                super().cmeth(arg) 

        # (copied from class doc)
       """
        pass 

    @staticmethod# known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature."""
        pass 

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self)."""
        pass 

    __self_class__ = property(lambda self: type(object))
   """the type of the instance invoking super(); may be None 

    :type: type
   """ 

    __self__ = property(lambda self: type(object))
   """the instance invoking super(); may be None 

    :type: type
   """ 

    __thisclass__ = property(lambda self: type(object))
   """the class invoking super() 

    :type: type
   """

method

时间: 2024-08-25 10:03:13

Python之String的相关文章

python中string模块各属性以及函数的用法

任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作. python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求: python的字符串属性函数 python的string模块 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 字符串属性函数 系统版本:CentOS release 6.2 (Final)2.6.32

python中string格式化

python中可以对string, int, float等数据类型进行格式化操作.下面举例来说明一些常用操作. 先贴出 python 对 String Formatting Operations 讲解的连接,后面的例子和内容都以它为参考. - flags '#' : '0' : 用'0'进行填充 '-'  : 左对齐 ' '  : 对于数字来说,整数前面会有个空格,负数不收到影响 '+' : 对数字添加正负号 - conversion list In[101]: print '%30.4fabc

在Python的string前面加上‘r’

在Python的string前面加上‘r’, 是为了告诉编译器不要转意backslash '\' . 例如,\n 在raw string中,是两个字符,\和n, 而不会转意为换行符.由于正则表达式和 \ 会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上'r'. 在Python的string前面加上'r'

python的string用法

s.strip().lstrip().rstrip(',') S.lower() #小写 S.upper() #大写 S.swapcase() #大小写互换 S.capitalize() #首字母大写 #分割 s = 'ab,cde,fgh,ijk'print(s.split(',')) #连接 delimiter = ','mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist) import str

python学习--string

1\string are immutable, which means you can't change an existing string. >>>greeting = 'Hello world!' >>>greeting[0] = 'J' TypeError: object does not support item assignment 2\The world in is a boolean operator that takes two strings and

PyQt的QString和python的string的区别

转载于http://blog.chinaunix.net/uid-200142-id-4018863.html python的string和PyQt的QString的区别 python string和PyQt的QString的区别 以下在Python2.6和PyQt4.4.4 for Python2,6环境下讨论: Python中有两种有关字符的类型:Python string object和Python Unicode object.主要使用Python string object进行数据输入

Python 教程——String的内置方法

Python为String类型提供了很多很有用的内置方法,这篇文章主要针对Python2.7的内置方法做一个测试列举,展示一下用途. 如果大家想看原版的,可以去这个网址看(https://docs.python.org/2/library/stdtypes.html#string-methods),但是这里是我自己的实践以及一些理解. 1. str.capitalize() 返回第一个字母大写的str str = "a string" str.capitalize()'A string

python中string.casefold和string.lower区别

string.casefold和string.lower 区别 python 3.3 引入了string.casefold 方法,其效果和 string.lower 非常类似,都可以把字符串变成小写,那么它们之间有什么区别?他们各自的应用场景? 对 Unicode 的时候用 casefold string.casefold官方说明: Casefolding is similar to lowercasing but more aggressive because it is intended t

乱码问题引申 python 中string和unicode

HtmlTestRunner的乱码问题 1生成的报告中,对print打印的数据都记录下来,但是数据有些会存在乱码.如下面.有些又没有乱码. 这到底是怎么回事呢? str=t.encode('utf-8') print str 第一个test我以utf-8编码,看来htmlTestRunner不是utf-8 编码. 为何第二个正确了呢? 第二个是unicode编码方式. 也就是说,可以被其他任何encode了. 原码中已这个进行编码,也就是说他设置为latin-1这种编码方式了.估计是作者自己国家