原始字符串

使用\转义或者r,这种方法在网站设置网站目录结构的时候非常管用。

>>> dos="c:\news"
>>> print dos
c:
ews
>>> dos="c:\\news"
>>> print dos
c:\news
>>> dos=r"c:\news" #r开头的字符串就是原始字符串
>>> print dos
c:\news
>>>

索引和切片

第一个字符是排序为0,空格也占用一个位置

>>> lang="study python"
>>> lang[0]
's'
>>> lang[2]
'u'
>>> "hello"[0]
'h'

根据字符查索引

>>> lang.index("py")

>>> lang="study python"
>>> lang.index("s") >>> lang.index("p") >>>

切片

得到的字符串是前包括后不包括(序号)

>>> lang="study python"
>>> lang[0:4] #从0到序号4之前的字符串
'stud'
>>> lang[1:]     #从序号1到最末的字符串
'tudy python'
>>> lang[:10]
'study pyth'    #得到序号10之前的字符,包括10
>>> lang[:]     #得到所有字符
'study python'

还有一种就是从右边开始切,注意[]中左边的数字要小于右边的数字

>>> a="python"
>>> a[-1]
'n'
>>> a[-3:-1]
'ho'

字符串的连接

>>> str1="hello"
>>> str2="world"
>>> str1+" "+str2 #字符串的连接
'hello world'

判断一个字符串是否包含另一个字符串

>>> "h" in "hello"
True
>>> "lll" in "hello"
False

求最值

一个字符串中的每个字符在计算机中都对应着一个编码。

>>> max("hello")
'o'
>>> min("hello")
'e'
>>> max("","")
''

查看一个字符对应的ASCII值

>>> ord("a")
97
>>> ord("b")
98
>>> ord("A")
65

字符串的比较

小于则返回-1,等于返回0,大于返回1,注意字符串之间的比较,先比较第一个字符,如果相等就比第二个字符,如果不相等则返回比较结果。

>>> cmp("a","b")
-1
>>> cmp("","")
-1
>>> cmp("abc","b")
-1

字符串之间的乘法

>>> "-"*10
'----------'
>>> "a"*10
'aaaaaaaaaa'

计算一个字符串之间的长度

返回的是int类型

>>> m=len("hello")
>>> m
5
>>> type(m)
<type 'int'>

字符串格式化输出

>>> "I like %s ,you know." %"Python"       %s是个占位符可以被其它字符串代替
'I like Python ,you know.'
>>> "%d years" %15
'15 years'
>>> "My wegiht is %.2f" %70.222
'My wegiht is 70.22'
>>> "My wegiht is %+.2f" %70.222
'My wegiht is +70.22'>>> print "My name is %s,I'm %d years." %("Keven",20) #也可以出现多个替代符
My name is Keven,I'm 20 years.
 

上面的方法常被认为是太古老的,下面是新的格式方法,即String .format的格式方法,{}作为占位符

>>> print "My name is {},I'm {} years.".format("Keven",20)
My name is Keven,I'm 20 years.
>>> print "My name is {name},I'm {age} years.".format(name="Keven",age=20) #如果觉得还不明确,可以采取这种对应的方法
My name is Keven,I'm 20 years.

常用的字符串方法

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

具体的方法可以用help查看

>>> help(str.upper)
Help on method_descriptor: upper(...)
S.upper() -> string Return a copy of the string S converted to uppercase.
(END)

实例:

1.split,分割,string向list转换

>>> "I love Python".split(" ")
['I', 'love', 'Python']
>>> "www.qq.com".split(".")
['www', 'qq', 'com'] >>> line = "Hello.I am keven.Welcome you."
>>> line.split(".",1)                  #指定分割的范围
['Hello', 'I am keven.Welcome you.']

2.strip,lstrip,rstrip,去空格

>>> " hello ".strip()
'hello'
>>> " hello ".lstrip()
'hello '
>>> " hello ".rstrip()
' hello'

3.字符大小写转换

  • S.upper()             变大写
  • S.lower                    变小写
  • S.capitalize()        首字母大写
  • S.isupper()              是否全是大写
  • S.islower                 是否全是小写
  • S.istitle()                 每个单词的第一个字母是否为大写
>>> "hello".upper()
'HELLO'
>>> "hello".istitle()
False
>>> "Hello".istitle()
True
>>> "Hello World".istitle()
True
>>> "Hello world".istitle()
False

join()连接字符串

>>> b= "www.qq.com".split(".")
>>> b
['www', 'qq', 'com']
>>> ".".join(b)
'www.qq.com'
>>> "/".join(b)
'www/qq/com'

Python避免中文乱码

1.在开头声明

#coding=utf-8

2.遇到字符(节)串,立刻转化为unicode,不要用str(),直接使用unicode()

>>> a=unicode('中',encoding='utf-8')
>>> a
u'\u4e2d'
>>> print a.encode('utf-8')

3.如果对文件操作,打开文件的时候,最好用 codecs.open,替代 open

import codecs
codecs.open('filename', encoding='utf8')

Python学习笔记3—字符串的更多相关文章

  1. python学习笔记(字符串操作、字典操作、三级菜单实例)

    字符串操作 name = "alex" print(name.capitalize()) #首字母大写 name = "my name is alex" pri ...

  2. 【Python学习笔记】字符串操作

    字符串的表示 python中的字符串是一个常量,可以使用单引号'',双引号""或三引号""" """来创建一个字符串常量 ...

  3. Python学习笔记(3)-字符串

    创建字符串 一对单引号或双引号 >>> 'hello world' 'hello world' >>> "hello world" 'hello ...

  4. Python学习笔记:字符串

    字符串 字符串定义:字符串可以使用一对单引号.双引号或三引号来定义,即便是单个字符也会当做字符串来处理(Python中没有字符类型,单个字符也就是只有一个字符的字符串而已). 原始字符串:字符串中反斜 ...

  5. python学习笔记(一)---字符串与列表

    字符串的一些处理 字符串的大小写 name="lonmar hb" print(name.upper())#全大写 print(name.lower())#全小写 print(na ...

  6. 【Python学习笔记】字符串拼接方法(5种)总结

    字符串的 5 种拼接方法: “+”号 “,”号 直接连接 格式化 多行字符串拼接 第一种:“+”号 print("Hello"+"Python") 打印结果: ...

  7. python学习笔记(二)-字符串方法

    python的字符串内建函数: #====================常用方法=============================name = 'besttest' new_name = n ...

  8. Python学习笔记----操作字符串

    1.字符串相加.列表相加.列表和字符串不能混着使用 #序列相加 a="hello" b="python" c=a+b print("字符串相加的结果& ...

  9. Python学习笔记之字符串

    一.字符串格式化 >>> format="Hello,%s. %s enough for ya?" >>> values=('World','H ...

随机推荐

  1. destoon 会员整合Ucenter/Discuz!/PHPWind教程

    首先进入 Destoon网站后台 -〉会员管理 -〉模块设置 -〉会员整合 假如需要整合的主站地址为 http://www.abc.com 论坛为 http://bbs.abc.com 1.整合Uce ...

  2. word 排版问题

    1.wps word为何设置了页边距后下面的页边距不变呢 在章节选项卡中,查看章节导航,有可能是文档分节了,光标所在的节已经调整,而你看到页是另一节 2.分栏 选中你要进行分栏的内容,进行分栏,也可以 ...

  3. 类型引起的bug

    1.当类型是整型时 $type = 12; 2.当类型是字符型 $type = '12';

  4. tomcat集群session共享

    Tomcat集群配置其实很简单,在Tomcat自带的文档中有详细的说明( /docs/cluster-howto.html ),只不过是英语的,对我这样的人来说很难懂   .   下面根据说下怎么配置 ...

  5. 关于AnimationState的测试

    修改time信息并不会立马生效,动画信息修改是在这一帧结束统一执行的. 当normalizedTime设置为0-1之外的值时,值并不会被约束回0-1范围,而动画会被约束播放到0-1之间的位置

  6. Poj(2407),Greater New York Regional 2015 (D)

    题目链接:http://poj.org/problem?id=2407 Relatives Time Limit: 1000MS   Memory Limit: 65536K Total Submis ...

  7. 华东交通大学2016年ACM“双基”程序设计竞赛 1001

    Problem Description 输入一个非负的int型整数,是奇数的话输出"ECJTU",是偶数则输出"ACM". Input 多组数据,每组数据输入一 ...

  8. Android中直播视频技术探究之---桌面屏幕视频数据源采集功能分析

    一.前言 之前介绍了Android直播视频中一种视频源数据采集:摄像头Camera视频数据采集分析 中介绍了利用Camera的回调机制,获取摄像头的每一帧数据,然后进行二次处理进行推流.现在我们在介绍 ...

  9. 2016年7月2日 星期六 --出埃及记 Exodus 14:29

    2016年7月2日 星期六 --出埃及记 Exodus 14:29 But the Israelites went through the sea on dry ground, with a wall ...

  10. tee 命令基本使用方法、输出到多个文件

    功能说明:读取标准输入的数据,并将其内容输出成文件.语  法:tee [-ai][--help][--version][文件...]补充说明:tee指令会从标准输入设备读取数据,将其内容输出到标准输出 ...