字符串:

赋值方法

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. 果园里有一堆苹果,一共n头(n大于1小于9)熊来分,第一头为小东,它把苹果均分n份后,多出了一个,它扔掉了这一个,拿走了自己的一份苹果,接着第二头熊重复这一过程,即先均分n份,扔掉一个然后拿走一份,以此类推直到最后一头熊都是这样(最后一头熊扔掉后可以拿走0个,也算是n份均分)。问最初这堆苹果最少有多少个。

    include "stdafx.h" // ConsoleApplication12.cpp : 定义控制台应用程序的入口点. // #include<iostream> ...

  2. Web大文件(夹)上传(断点续传)控件-Xproer.HttpUploader6

    版权所有 2009-2017荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/in ...

  3. git 工具 - 子模块(submodule)

    From: https://git-scm.com/book/zh/v2/Git-%E5%B7%A5%E5%85%B7-%E5%AD%90%E6%A8%A1%E5%9D%97 子模块 有种情况我们经常 ...

  4. access变转换为mysql表工具

    1.一个是国外软件,名字叫Access2MySQL,下载地址:http://www.pc6.com/softview/SoftView_7187.html 2.第二款软件是月光博客写的一个小软件:DB ...

  5. 开源监控系统Prometheus介绍

    前言 Prometheus是CNCF的一个开源项目,Google BorgMon监控系统的开源版本,是一个系统和服务的监控系统.周期性采集metrics指标,匹配规则和展示结果,以及触发某些条件的告警 ...

  6. Vue 填坑系列(持续更新...)

    1.遇到页面显示不更新,数据已更新情况 vue-cli中: this.$nextTick(function () { this.x=x; })     以js引入vue的网页中: this.$set( ...

  7. Delphi 完全时尚手册之 Visual Style 篇

    这里先说说两个概念:Theme(主题)和 Visual Style .Theme 最早出现在 Microsoft Plus! for Windows 95 中,是 Windows 中 Wallpape ...

  8. 一个小公司的前端笔试HTML CSS JS

    网上有这套题的答案,版本也很多,我做了很多参考.本文就当个小笔记,可能有错误,还望指正~ 第1章  Html篇 1. 你做的网页在哪些浏览器测试过?这些浏览器的内核分别是什么? 浏览器类型 内核 Fi ...

  9. error LNK2022: metadata operation failed (801311D6) : Differing number of methods in duplicated types

    本文主要是记录一个C++编译错误的解决方案,具体错误请看本文标题. 这个错误主要是由Managed C++的增量编译导致的,这是VS 2008的一个bug,在VS 2010已经修复,我使用的正式201 ...

  10. 20145239 Linux下常用的ls命令总结

    20145239 Linux下常用的ls命令总结 通过学习本周的教学视频和要求掌握的内容,发现ls命令被使用的次数非常多,但作为一个初学者,可能我只会ls或者顶多ls -l两种用法.但其实ls是一个非 ...