Python开发(基础):字符串

简介:
  • 字符串常用方法说明
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-

    # class str(basestring):
    #     """
    #     str(object='') -> string
    #
    #     Return a nice string representation of the object.
    #     If the argument is a string, the return value is the same object.
    #     """
    #
    #     def capitalize(self) # real signature unknown; restored from __doc__
    #         """
    #          首字母大写
    #         S.capitalize() -> string
    #
    #         Return a copy of the string S with only its first character
    #         capitalized.
    #         """
    #         return ""
    #
    str_capitalize = 'welcome'
    print str_capitalize.capitalize()
    #输出:Welcome

    #     def center(self, width, fillchar=None):  # real signature unknown; restored from __doc__
    #         """
    #         原字符串居中显示,两边可选择填充字符
    #         S.center(width[, fillchar]) -> string
    #
    #         Return S centered in a string of length width. Padding is
    #         done using the specified fill character (default is a space)
    #         """
    #         return ""
    str_center = 'hello'
    print str_center.center(20,'*')
    #输出:*******hello********
    #     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
    #
    str_count = 'helikdk;a'
    print str_count.count('k')
    #输出:2
    #     def decode(self, encoding=None, errors=None):  # real signature unknown; restored from __doc__
    #         """
    #         字符串解码
    #         S.decode([encoding[,errors]]) -> object
    #
    #         Decodes S using the codec registered for encoding. encoding defaults
    #         to the default encoding. errors may be given to set a different error
    #         handling scheme. Default is 'strict' meaning that encoding errors raise
    #         a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
    #         as well as any other name registered with codecs.register_error that is
    #         able to handle UnicodeDecodeErrors.
    #         """
    #         return object()
    #
    #     def encode(self, encoding=None, errors=None):  # real signature unknown; restored from __doc__
    #         """
    #         字符串编码
    #         S.encode([encoding[,errors]]) -> object
    #
    #         Encodes S using the codec registered for encoding. encoding defaults
    #         to the default encoding. 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 is able to handle UnicodeEncodeErrors.
    #         """
    #         return object()
    #
    #     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
    #
    #     def expandtabs(self, tabsize=None):  # real signature unknown; restored from __doc__
    #         """
    #         将字符串中的tab键替换成空格(默认是8个空格),也可自己指定
    #         S.expandtabs([tabsize]) -> string
    #
    #         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 ""
    #
    str_expandtabs = 'hello\talex'
    print str_expandtabs
    print str_expandtabs.expandtabs(20)
    #输出:hello  alex
    #      hello               alex
    #     def find(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
    #         """
    #         查找字符串中子字符串第一次出现的位置(下标从0开始),也可指定从某个位置开始查找,或结束查找,
    #         如果找不到就返回-1
    #         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
    #
    str_find = 'kdlafjdklkdla'
    print str_find.find('la',4)
    #输出:11
    #     def format(self, *args, **kwargs):  # known special case of str.format
    #         """
    #         通过通配符来格式化字符串
    #         S.format(*args, **kwargs) -> string
    #
    #         Return a formatted version of S, using substitutions from args and kwargs.
    #         The substitutions are identified by braces ('{' and '}').
    #         """
    #         pass
    #
    str_format = 'hell {0},age {1}'
    print str_format.format('alex',19)
    #输出:hell alex,age 19
    #     def index(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
    #         """
    #         查找字符串中子字符串第一次出现的位置(下标从0开始),也可指定从某个位置开始查找,或结束查找,找不到会报错,功能同find类似
    #         S.index(sub [,start [,end]]) -> int
    #
    #         Like S.find() but raise ValueError when the substring is not found.
    #         """
    #         return 0
    str_index = 'kd;fjdkl;sfjkd;akd'
    print  str_index.index('fj')
    #输出:3

    #     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
    #
    str_isalnum = 'dafdfdk;j123'
    print str_isalnum.isalnum()
    #输出:False
    #     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
    #
    #     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
    #
    #     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
    #
    #     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
    #
    #     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. uppercase characters may only follow uncased
    #         characters and lowercase characters only cased ones. Return False
    #         otherwise.
    #         """
    #         return False
    #
    #     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
    #
    #     def join(self, iterable):  # real signature unknown; restored from __doc__
    #         """
    #         将list、元组等通过一个字符或字符串连接成一个字符串
    #         S.join(iterable) -> string
    #
    #         Return a string which is the concatenation of the strings in the
    #         iterable.  The separator between elements is S.
    #         """
    #         return ""
    #
    li = ['alex','age']
    print '.'.join(li)
    #输出:alex.age
    #   def ljust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
    #         """
    #         左对齐,右边填充所给的字符
    #         S.ljust(width[, fillchar]) -> string
    #
    #         Return S left-justified in a string of length width. Padding is
    #         done using the specified fill character (default is a space).
    #         """
    #         return ""
    #
    str_ljust = '     hello,where are you from ? ]'
    print str_ljust.ljust(40,'*')
    print str_ljust.ljust(50,"*")
    #输出:
    # hello,where are you from ? ]*******
    # hello,where are you from ? ]*****************
    #     def lower(self):  # real signature unknown; restored from __doc__
    #         """
    #         将字符串转换为小写
    #         S.lower() -> string
    #
    #         Return a copy of the string S converted to lowercase.
    #         """
    #         return ""
    #
    #     def lstrip(self, chars=None):  # real signature unknown; restored from __doc__
    #         """
    #         去掉字符串左边的空格
    #         S.lstrip([chars]) -> string or unicode
    #
    #         Return a copy of the string S with leading whitespace removed.
    #         If chars is given and not None, remove characters in chars instead.
    #         If chars is unicode, S will be converted to unicode before stripping
    #         """
    #         return ""
    #
    print '   dkla;  fda;   '.lstrip()
    #     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
    #
    str_partition = 'headseptail'
    print str_partition.partition('sep')
    #输出:('head', 'sep', 'tail')
    #     def replace(self, old, new, count=None):  # real signature unknown; restored from __doc__
    #         """
    #         替换字符串中的某个部份,可经指定替换几次
    #         S.replace(old, new[, count]) -> string
    #
    #         Return a copy of string 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 ""
    #
    #     def rfind(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
    #         """
    #         字符串中查找某个字符第一次出现的位置,从右边开始,用法同find(默认从左边开始)
    #         S.rfind(sub [,start [,end]]) -> int
    #
    #         Return the highest 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
    #
    print 'dklfkd;fjdklsa'.rfind('dk')
    #输出:9
    #     def rindex(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
    #         """
    #         字符串中查找某个字符第一次出现的位置,从右边开始,用法同index(默认从左边开始)
    #         S.rindex(sub [,start [,end]]) -> int
    #
    #         Like S.rfind() but raise ValueError when the substring is not found.
    #         """
    #         return 0
    #
    #     def rjust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
    #         """
    #         右对齐,左边填充所给的字符
    #         S.rjust(width[, fillchar]) -> string
    #
    #         Return S right-justified in a string of length width. Padding is
    #         done using the specified fill character (default is a space)
    #         """
    #         return ""
    #
    print '   kfdls;k kldjklfdlk     '.rjust(50,'*')
    #输出:************************   kfdls;k kldjklfdlk
    #     def rpartition(self, sep):  # real signature unknown; restored from __doc__
    #         """
    #         用法同partition ,只是从右边开始
    #         S.rpartition(sep) -> (head, sep, tail)
    #
    #         Search for the separator sep in S, starting at the end of S, and return
    #         the part before it, the separator itself, and the part after it.  If the
    #         separator is not found, return two empty strings and S.
    #         """
    #         pass
    #
    #     def rsplit(self, sep=None, maxsplit=None):  # real signature unknown; restored from __doc__
    #         """
    #         用法同split
    #         S.rsplit([sep [,maxsplit]]) -> list of strings
    #
    #         Return a list of the words in the string 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 or is None, any whitespace string
    #         is a separator.
    #         """
    #         return []
    s_rsplit = 'dkls;jfkdlak;jkdls;af'
    print s_rsplit.rsplit(';')
    #输出:['dkls', 'jfkdlak', 'jkdls', 'af']
    #     def rstrip(self, chars=None):  # real signature unknown; restored from __doc__
    #         """
    #         去掉字符串右边的空格
    #         S.rstrip([chars]) -> string or unicode
    #
    #         Return a copy of the string S with trailing whitespace removed.
    #         If chars is given and not None, remove characters in chars instead.
    #         If chars is unicode, S will be converted to unicode before stripping
    #         """
    #         return ""
    #
    #     def split(self, sep=None, maxsplit=None):  # real signature unknown; restored from __doc__
    #         """
    #         要据所给字符串字符串拆分成一个list
    #         S.split([sep [,maxsplit]]) -> list of strings
    #
    #         Return a list of the words in the string 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 []
    #
    #     def splitlines(self, keepends=False):  # real signature unknown; restored from __doc__
    #         """
    #         S.splitlines(keepends=False) -> 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 []
    #
    #     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
    #
    #     def strip(self, chars=None):  # real signature unknown; restored from __doc__
    #         """
    #         去掉字符串左右两边的窗格
    #         S.strip([chars]) -> string or unicode
    #
    #         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.
    #         If chars is unicode, S will be converted to unicode before stripping
    #         """
    #         return ""
    #
    print '  dksl  klds  '.strip()
    #输出:dksl  klds
    #     def swapcase(self):  # real signature unknown; restored from __doc__
    #         """
    #         大小写转换,大写变小写,小写变大写
    #         S.swapcase() -> string
    #
    #         Return a copy of the string S with uppercase characters
    #         converted to lowercase and vice versa.
    #         """
    #         return ""
    #
    print 'AkdlNkdlKDKLda;'.swapcase()
    #输出:aKDLnKDLkdklDA;
    #     def title(self):  # real signature unknown; restored from __doc__
    #         """
    #         字符串首字母大写,其他全部转为小写
    #         S.title() -> string
    #
    #         Return a titlecased version of S, i.e. words start with uppercase
    #         characters, all remaining cased characters have lowercase.
    #         """
    #         return ""
    #
    print 'kdlsaKDlk'.title()
    #输出:Kdlsakdlk
    #     def translate(self, table, deletechars=None):  # real signature unknown; restored from __doc__
    #         """
    #         S.translate(table [,deletechars]) -> string
    #
    #         Return a copy of the string S, where all characters occurring
    #         in the optional argument deletechars are removed, and the
    #         remaining characters have been mapped through the given
    #         translation table, which must be a string of length 256 or None.
    #         If the table argument is None, no translation is applied and
    #         the operation simply removes the characters in deletechars.
    #         """
    #         return ""
    #
    #     def upper(self):  # real signature unknown; restored from __doc__
    #         """
    #         字符串全部转为大写
    #         S.upper() -> string
    #
    #         Return a copy of the string S converted to uppercase.
    #         """
    #         return ""
    #
    #     def zfill(self, width):  # real signature unknown; restored from __doc__
    #         """
    #         根据所给宽度,将字符串左边不够的位置上填充0
    #         S.zfill(width) -> string
    #
    #         Pad a numeric string S with zeros on the left, to fill a field
    #         of the specified width.  The string S is never truncated.
    #         """
    #         return ""
    print '1000'.zfill(8)
    #输出:00001000
    #     def _formatter_field_name_split(self, *args, **kwargs):  # real signature unknown
    #         pass
    #
    #     def _formatter_parser(self, *args, **kwargs):  # real signature unknown
    #         pass
    #
    #     def __add__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__add__(y) <==> x+y """
    #         pass
    #
    #     def __contains__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__contains__(y) <==> y in x """
    #         pass
    #
    #     def __eq__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__eq__(y) <==> x==y """
    #         pass
    #
    #     def __format__(self, format_spec):  # real signature unknown; restored from __doc__
    #         """
    #         S.__format__(format_spec) -> string
    #
    #         Return a formatted version of S as described by format_spec.
    #         """
    #         return ""
    #
    #     def __getattribute__(self, name):  # real signature unknown; restored from __doc__
    #         """ x.__getattribute__('name') <==> x.name """
    #         pass
    #
    #     def __getitem__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__getitem__(y) <==> x[y] """
    #         pass
    #
    #     def __getnewargs__(self, *args, **kwargs):  # real signature unknown
    #         pass
    #
    #     def __getslice__(self, i, j):  # real signature unknown; restored from __doc__
    #         """
    #         x.__getslice__(i, j) <==> x[i:j]
    #
    #                    Use of negative indices is not supported.
    #         """
    #         pass
    #
    #     def __ge__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__ge__(y) <==> x>=y """
    #         pass
    #
    #     def __gt__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__gt__(y) <==> x>y """
    #         pass
    #
    #     def __hash__(self):  # real signature unknown; restored from __doc__
    #         """ x.__hash__() <==> hash(x) """
    #         pass
    #
    #     def __init__(self, string=''):  # known special case of str.__init__
    #         """
    #         str(object='') -> string
    #
    #         Return a nice string representation of the object.
    #         If the argument is a string, the return value is the same object.
    #         # (copied from class doc)
    #         """
    #         pass
    #
    #     def __len__(self):  # real signature unknown; restored from __doc__
    #         """ x.__len__() <==> len(x) """
    #         pass
    #
    #     def __le__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__le__(y) <==> x<=y """
    #         pass
    #
    #     def __lt__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__lt__(y) <==> x<y """
    #         pass
    #
    #     def __mod__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__mod__(y) <==> x%y """
    #         pass
    #
    #     def __mul__(self, n):  # real signature unknown; restored from __doc__
    #         """ x.__mul__(n) <==> x*n """
    #         pass
    #
    #     @staticmethod  # known case of __new__
    #     def __new__(S, *more):  # real signature unknown; restored from __doc__
    #         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
    #         pass
    #
    #     def __ne__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__ne__(y) <==> x!=y """
    #         pass
    #
    #     def __repr__(self):  # real signature unknown; restored from __doc__
    #         """ x.__repr__() <==> repr(x) """
    #         pass
    #
    #     def __rmod__(self, y):  # real signature unknown; restored from __doc__
    #         """ x.__rmod__(y) <==> y%x """
    #         pass
    #
    #     def __rmul__(self, n):  # real signature unknown; restored from __doc__
    #         """ x.__rmul__(n) <==> n*x """
    #         pass
    #
    #     def __sizeof__(self):  # real signature unknown; restored from __doc__
    #         """ S.__sizeof__() -> size of S in memory, in bytes """
    #         pass
    #
    #     def __str__(self):  # real signature unknown; restored from __doc__
    #         """ x.__str__() <==> str(x) """
    #         pass
    #
    #
    # bytes = str

本文转自  wbb827  51CTO博客,原文链接:http://blog.51cto.com/wbb827/1933471
相关文章
|
14天前
|
算法 测试技术 开发者
性能优化与代码审查:提升Python开发效率
【4月更文挑战第9天】本文强调了Python开发中性能优化和代码审查的重要性。性能优化包括选择合适数据结构、使用生成器和避免全局变量,而代码审查涉及遵循编码规范、使用静态代码分析工具和编写单元测试。这些实践能提升代码效率和可维护性,促进团队协作。
|
16天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
1月前
|
大数据 Python
使用Python查找字符串中包含的多个元素
本文介绍了Python中查找字符串子串的方法,从基础的`in`关键字到使用循环和条件判断处理多个子串,再到利用正则表达式`re模块`进行复杂模式匹配。文中通过实例展示了如何提取用户信息字符串中的用户名、邮箱和电话号码,并提出了优化策略,如预编译正则表达式和使用生成器处理大数据。
20 1
|
5天前
|
前端开发 Java Go
开发语言详解(python、java、Go(Golong)。。。。)
开发语言详解(python、java、Go(Golong)。。。。)
|
7天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
44 0
|
8天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
8天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
12天前
|
JavaScript 前端开发 关系型数据库
金融技术解决方案:用Python和Vue开发加密货币交易平台
【4月更文挑战第11天】本文介绍了如何使用Python和Vue.js构建加密货币交易平台。首先确保安装了Python、Node.js、数据库系统和Git。后端可选择Flask或Django框架,通过RESTful API处理交易。前端利用Vue.js、Vuex和Vue Router创建用户友好的界面,并用Axios与后端通信。这种架构促进团队协作,提升代码质量和平台功能。
|
13天前
|
JavaScript 前端开发 Docker
全栈开发实战:结合Python、Vue和Docker进行部署
【4月更文挑战第10天】本文介绍了如何使用Python、Vue.js和Docker进行全栈开发和部署。Python搭配Flask创建后端API,Vue.js构建前端界面,Docker负责应用的容器化部署。通过编写Dockerfile,将Python应用构建成Docker镜像并运行,前端部分使用Vue CLI创建项目并与后端交互。最后,通过Nginx和另一个Dockerfile部署前端应用。这种组合提升了开发效率,保证了应用的可维护性和扩展性,适合不同规模的企业使用。
|
16天前
|
Java 索引 Python
Python标准数据类型-字符串常用方法(下)
Python标准数据类型-字符串常用方法(下)
21 1