字符串:

赋值方法

a = 'name'

a = str('name')

字符串的方法:

 #!/usr/bin/env python
class str(object):
"""
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'.
"""
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 "" def casefold(self): # real signature unknown; restored from __doc__
'''全部转换为小写'''
"""
S.casefold() -> str Return a version of S suitable for caseless comparisons.
"""
return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
'''内容居中,width:总长度,fillchar:空白处填充内容,默认无'''
"""
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 "" 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 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
'''编码,针对unicode'''
"""
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"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
'''判断是否以特定值结尾,也可以是一个元组。如果是则为真(True)'''
"""
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=8): # real signature unknown; restored from __doc__
'''将一个tab键转换为空格,默认为8个空格'''
"""
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 "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
'''寻找子序列的位置,如果没有找到则返回 -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 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 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 "" 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 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 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 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 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 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 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 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 def isprintable(self): # real signature unknown; restored from __doc__
'''内容是否都是可见的字符,不可见的包括tab键,换行符。空格为可见字符'''
"""
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): # 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. upper- and titlecase 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__
'''连接,以S作为分隔符,把所有iterable中的元素合并成一个新的字符串'''
"""
S.join(iterable) -> str Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
'''左对齐,width 字符串的长度,右侧以fillchar填充,默认为空'''
"""
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 "" def lower(self): # real signature unknown; restored from __doc__
'''所有字母大写变小写,返回一个小写的副本'''
"""
S.lower() -> str 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]) -> 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 "" 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 def partition(self, sep): # real signature unknown; restored from __doc__
'''分割,把字符以sep分割为 前 中 后 三个部分'''
"""
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 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
'''替换,old替换为new,可以指定次数(count)'''
"""
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 ""
###########################################################
#所有以r开头和上面一样的方法,都和上面反方向(即从右到左)#
###########################################################
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
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 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
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]) -> str Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return "" def rpartition(self, sep): # real signature unknown; restored from __doc__
"""
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=-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): # real signature unknown; restored from __doc__
'''分割,以什么分割,maxsplit分割次数'''
"""
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 [] 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 [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
'''是否以self起始,可以指定开始和结束位置'''
"""
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]) -> 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 "" 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 "" def title(self): # real signature unknown; restored from __doc__
'''标题化,即首字母大写其余字母为小写'''
"""
S.title() -> str Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
"""
return "" 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 "" def upper(self): # real signature unknown; restored from __doc__
'''小写字母转换为大写'''
"""
S.upper() -> str Return a copy of S converted to uppercase.
"""
return "" def zfill(self, width): # real signature unknown; restored from __doc__
'''返回width长度的字符串,原字符串右对齐,前面填充 0 '''
"""
S.zfill(width) -> str 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 ""

str

示例:

####
capitalize()
>>> name = 'binges wang'
>>> name.capitalize()
'Binges wang'
####
casefold()
>>> name = 'Binges Wang'
>>> name.casefold()
'binges wang'
####
center()
>>> name = 'binges'
>>> name.center(10)
'  binges  '
>>> name.center(10,'#')
'##binges##'
####
endswith()
>>> name = 'binges'
>>> name.endswith('s')
True
>>> name.endswith('es')
True
>>> name.endswith('ed')
False
####
find()
>>> name = 'binges wang'
>>> name.find('s')
5
>>> name.find('x')
-1
>>> name.find('g')
3
>>> name.find('an')
8
####
index()
>>> name = 'binges wang'
>>> name.index('a')
8
>>> name.index('s')
5
>>> name.index('an')
8
>>> name.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
####
isalnum()
>>> name = 'binges'
>>> name.isalnum()
True
>>> name = 'binges 12'
>>> name.isalnum()
False
>>> name = 'binges12'
>>> name.isalnum()
True
>>> age = '12'
>>> age.isalnum()
True
####
isalpha()
>>> name = 'binges12'
>>> name.isalpha()
False
>>> name = 'binges wang'
>>> name.isalpha()
False
>>> name = 'binges'
>>> name.isalpha()
True
####
isdigit()
>>> age = '23'
>>> age.isdigit()
True
>>> age = '23 '
>>> age.isdigit()
False
>>> age = '23.5'
>>> age.isdigit()
False
####
isidentifier()
>>> name = 'binges wang'
>>> name.isidentifier()
False
>>> name = 'binges'
>>> name.isidentifier()
True
####
islower()
>>> name = 'binges'
>>> name.islower()
True
>>> name = 'binges wang'
>>> name.islower()
True
>>> name = 'binges 12'
>>> name.islower()
True
>>> name = 'binges Wang'
>>> name.islower()
False
####
isprintable()
>>> name = 'binges      wang'
>>> name.isprintable()
False
>>> name = 'binges wang'
>>> name.isprintable()
True
>>> name = 'binges\nwang'
>>> name.isprintable()
False
####
isspace()
>>> name = '  '    #两个空格
>>> name.isspace()
True
>>> name = '    '    #一个tab键
>>> name.isspace()
True
>>> name = 'bings wang'
>>> name.isspace()
False
####
istitle()
>>> name = 'binges wang'
>>> name.istitle()
False
>>> name = 'Binges wang'
>>> name.istitle()
False
>>> name = 'Binges Wang'
>>> name.istitle()
True
####
isupper()
>>> name = 'BINGEs'
>>> name.isupper()
False
>>> name = 'BINGES'
>>> name.isupper()
True
>>> name = 'BINGES WANG'
>>> name.isupper()
True
####
join()
>>> a = ' '    #一个空格
>>> a.join(b)
'b i n g e s'
####
ljust()
>>> name = 'binges'
>>> name.ljust(10)
'binges    '
>>> name.ljust(10,'&')
'binges&&&&'
####
lower()
>>> name = 'BinGes WanG'
>>> name.lower()
'binges wang'
>>> name
'BinGes WanG'
####
lstrip()
>>> name = '    binges wang'    #一个空格和一个tab键
>>> name.lstrip()
'binges wang'
####
partition('n')
>>> name = 'binges wang'
>>> name.partition('n')
('bi', 'n', 'ges wang')
####
replace()
>>> name = 'binges wang'
>>> name.replace('n','w')
'biwges wawg'
>>> name
'binges wang'
>>> name.replace('n','w',1)
'biwges wang'
####
startswith()
>>> name = 'binges'
>>> name.startswith('b')
True
>>> name.startswith('bd')
False
>>> name.startswith('n',1,5)
False
>>> name.startswith('n',2,5)
True
####
split()
>>> name = 'binges'
>>> name.split('n')
['bi', 'ges']
>>> name = 'binges wang'
>>> name.split('n')
['bi', 'ges wa', 'g']
>>> name.split('n',1)
['bi', 'ges wang']
####
strip()
>>> name = '    binges  wang    '    #空白处都为一个空格和一个tab键
>>> name.strip()
'binges \twang'
####
swapcase()
>>> name = 'BinGes WanG'
>>> name.swapcase()
'bINgES wANg'
####
title()
>>> name = 'BinGes WanG'
>>> name.title()
'Binges Wang'
####
upper()
>>> name
'BinGes WanG'
>>> name.upper()
'BINGES WANG'
####
zfill(10)
>>> name = 'binges'
>>> name.zfill(10)
'0000binges'
####
 
 

python基础知识-字符串的更多相关文章

  1. python基础知识——字符串详解

    大多数人学习的第一门编程语言是C/C++,个人觉得C/C++也许是小白入门的最合适的语言,但是必须承认C/C++确实有的地方难以理解,初学者如果没有正确理解,就可能会在使用指针等变量时候变得越来越困惑 ...

  2. python基础知识字符串与元祖

    https://blog.csdn.net/hahaha_yan/article/details/78905495 一.字符串的类型 ##表示字符串: 'i like the world' " ...

  3. Python开发【第二篇】:Python基础知识

    Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...

  4. python 基础知识(一)

    python 基础知识(一) 一.python发展介绍 Python的创始人为Guido van Rossum.1989年圣诞节期间,在阿姆斯特丹,Guido为了打发圣诞节的无趣,决心开发一个新的脚本 ...

  5. python 爬虫与数据可视化--python基础知识

    摘要:偶然机会接触到python语音,感觉语法简单.功能强大,刚好朋友分享了一个网课<python 爬虫与数据可视化>,于是在工作与闲暇时间学习起来,并做如下课程笔记整理,整体大概分为4个 ...

  6. python基础知识小结-运维笔记

    接触python已有一段时间了,下面针对python基础知识的使用做一完整梳理:1)避免‘\n’等特殊字符的两种方式: a)利用转义字符‘\’ b)利用原始字符‘r’ print r'c:\now' ...

  7. Python基础知识(五)

    # -*- coding: utf-8 -*-# @Time : 2018-12-25 19:31# @Author : 三斤春药# @Email : zhou_wanchun@qq.com# @Fi ...

  8. Python 基础知识(一)

    1.Python简介 1.1.Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯特丹打发时 ...

  9. python基础知识部分练习大全

    python基础知识部分练习大全   1.执行 Python 脚本的两种方式 答:1.>>python ../pyhton.py 2. >>python.py   #必须在首行 ...

随机推荐

  1. javascript onclick中post提交

    对post提交进行封装: function post(URL, PARAMS) { var temp = document.createElement("form"); temp. ...

  2. 11 linux nginx上安装ecshop 案例

    一: nginx上安装ecshop 案例 (1)解压到 nginx/html下 浏览器访问:127.0.0.1/ecshop/index.php 出现错误:not funod file 原因:ngin ...

  3. linux memcached php 整合

    http://blog.csdn.net/liruxing1715/article/details/8269563

  4. shader学习之一:Properties语义块支持的数据类型

    _Int ("Int",Int)=2为:变量名("面板显示的名称",数据类型) 对于Int,Float,Range这些数字类型的属性,默认值为单独的数字.对于贴 ...

  5. linux 配置 skywalking

    linux安装elasticsearch 一.检测是否已经安装的elasticsearch ps -aux|grep elasticsearch 二.下载elasticsearch (1)下载网站为: ...

  6. mysql系列之7.mysql读写分离

    准备 下载如下linux安装包 jdk-6u31-linux-x64-rpm.bin amoeba-mysql-binary-2.2.0.tar.gz # crontab -e  //同步时间 */ ...

  7. 获取系统 SID

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/hadstj/article/details/26399533 获取系统 SID ((gwmi win ...

  8. MySQL——存储引擎

    核心知识点 1.InnoDB:数据和索引存放在单独的文件,聚簇索引,行级锁,事务,MVCC 2.MyISAM: (1)缺点:不支持事务和表级锁,因为不支持表锁,锁颗粒比较大,因此适合只读和小文件. ( ...

  9. Ruby操作数据库基本步骤

    1.rails g model university name:string 2.model has_many :colleges belongs_to :university has_one :us ...

  10. ZOJ - 1504 Slots of Fun 【数学】

    题目链接 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1504 题意 给出一串字符串 里面的每个字符的位置 都按照题目的意 ...