- 字符串常用方法说明
#!/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
Python开发(基础):字符串
时间: 2024-10-12 03:19:02
Python开发(基础):字符串的相关文章
Python 开发基础-字符串类型讲解(字符串方法)-1
s = 'Hello World!' print(s.capitalize()) #第一个字母大写,其余小写# 输出:Hello world!print(s.swapcase())#大写变小写,小写变大写#输出:hELLO wORLD!print(s.casefold())#全变小写#输出:hello world!print(s.center(50,'-'))#S字符字符串在总50宽度的居中位置,两边用"-"填充#输出:-------------------Hello World!--
python开发基础:字符串操作
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 4 #strip 方法用于移除字符串头尾指定的字符(默认为空格). 5 #str.strip([chars]); 6 # chars移除字符串头尾指定的字符. 这是一个包含的关系 7 name = "*joker**" 8 print(name.strip("*")) 9 print(name.lstrip("*")) #去除左边 10 print(n
Python开发基础-Day2-流程控制、数字和字符串处理
流程控制 条件判断 if单分支:当一个"条件"成立时执行相应的操作. 语法结构: if 条件: command 流程图: 示例:如果3大于2,那么输出字符串"very good" #!/usr/bin/env python # -*- coding: utf-8 -*- if 3 > 2: print("very good") if双分支:当"条件成立"时候执行一个操作,或者"条件不成立"执行另外一个
python开发基础篇(一)
变量及其定义规范 1 #变量名(相当于门牌号,指向值所在的空间),等号,变量值 2 name='Egon' 3 sex='male' 4 age=18 5 level=10 变量的定义规范 #1. 变量名只能是 字母.数字或下划线的任意组合 #2. 变量名的第一个字符不能是数字 #3. 关键字不能声明为变量名['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', '
Python开发基础-Day23try异常处理、socket套接字基础1
异常处理 错误 程序里的错误一般分为两种: 1.语法错误,这种错误,根本过不了python解释器的语法检测,必须在程序执行前就改正 2.逻辑错误,人为造成的错误,如数据类型错误.调用方法错误等,这些解释器是不会进行检测的,只有在执行的过程中才能抛出的错误 异常 异常是python解释器在运行程序的过程中遇到错误所抛出的信息,如: Python异常种类: 常用异常: 1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x 2 IOError 输入/输出异
Python开发基础-Day1-python入门
编程语言分类 机器语言 使用二进制代码直接编程,直接与硬件交互,执行速度非常快,灵活,但是开发难度高,开发效率低下,缺乏移植性. 汇编语言 对机器语言指令进行了英文封装,较机器语言容易记忆,直接与硬件交互,执行速度快,执行文件小,但是开发难度相对也很高,开发效率低 高级语言 语法简单,容易理解,开发难度低效率高,开发后测试方便,但是开发的程序需要经过转换才能执行,所以执行效率相对慢,可移植性高. 解释执行:代码执行时候,解释器按照源代码文件中的内容,一条条解释并运行,相对编译执行速度慢,但出错方
Python开发基础--- Event对象、队列和多进程基础
Event对象 用于线程间通信,即程序中的其一个线程需要通过判断某个线程的状态来确定自己下一步的操作,就用到了event对象 event对象默认为假(Flase),即遇到event对象在等待就阻塞线程的执行. 示例1:主线程和子线程间通信,代码模拟连接服务器 1 import threading 2 import time 3 event=threading.Event() 4 5 def foo(): 6 print('wait server...') 7 event.wait() #括号里可
Python开发基础-Day31 Event对象、队列和多进程基础
Event对象 用于线程间通信,即程序中的其一个线程需要通过判断某个线程的状态来确定自己下一步的操作,就用到了event对象 event对象默认为假(Flase),即遇到event对象在等待就阻塞线程的执行. 示例1:主线程和子线程间通信,代码模拟连接服务器 1 import threading 2 import time 3 event=threading.Event() 4 5 def foo(): 6 print('wait server...') 7 event.wait() #括号里可
Python开发基础-Day14正则表达式和re模块
正则表达式 就其本质而言,正则表达式(或 re)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行. 字符匹配(普通字符,元字符): 1 普通字符(完全匹配):大多数字符和字母都会和自身匹配 1 >>> import re 2 >>> res='hello world good morning' 3 >>> re.findall(
Python开发基础----异常处理、socket套接字基础1
异常处理 错误 程序里的错误一般分为两种: 1.语法错误,这种错误,根本过不了python解释器的语法检测,必须在程序执行前就改正 2.逻辑错误,人为造成的错误,如数据类型错误.调用方法错误等,这些解释器是不会进行检测的,只有在执行的过程中才能抛出的错误 异常 异常是python解释器在运行程序的过程中遇到错误所抛出的信息,如: Python异常种类: 常用异常: 1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x 2 IOError 输入/输出异