基础知识:字符串

  成字符串

Python中可以使用一对单引号''或者双引号""生成字符串。
  

简单操作

   加法:
  

字符串与数字相乘:
  


字符串长度:
  
   

字符串方法

Python是一种面向对象的语言,面向对象的语言中一个必不可少的元素就是方法,而字符串是对象的一种,所以有很多可用的方法。

跟很多语言一样,Python使用以下形式来调用方法:

对象.方法(参数)

分割

s.split()将s按照空格(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串。
  
s.split(sep)以给定的sep为分隔符对s进行分割。
  

 


连接

与分割相反,s.join(str_sequence)的作用是以s为连接符将字符串序列str_sequence中的元素连接起来,并返回连接后得到的新字符串:
s = ' '
s.join(numbers)    结果:'1 2 3 4 5'

s = ','
s.join(numbers)    结果:'1,2,3,4,5'


替换

s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部分part2,并返回新的字符串。
s = "hello world"
s.replace('world', 'python')    结果:'hello python'

此时,s的值并没有变化,替换方法只是生成了一个新的字符串。
s    结果:'hello world'


大小写转换

s.upper()方法返回一个将s中的字母全部大写的新字符串。
s.lower()方法返回一个将s中的字母全部小写的新字符串。
"hello world".upper()    结果:'HELLO WORLD'

这两种方法也不会改变原来s的值:
s = "HELLO WORLD"
print s.lower()    结果:hello world
print s    结果:HELLO WORLD

去除多余空格

s.strip()返回一个将s两端的多余空格除去的新字符串。
s.lstrip()返回一个将s开头的多余空格除去的新字符串。
s.rstrip()返回一个将s结尾的多余空格除去的新字符串。
 

s的值依然不会变化:
  

  

  
 

更多方法    可以使用dir函数查看所有可以使用的方法:

dir(s)
['__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']
 

多行字符串    Python 用一对 """ 或者 ''' 来生成多行字符串:

a = """hello world.
it is a nice day."""
print a
 
结果:
hello world.
it is a nice day.
在储存时,我们在两行字符间加上一个换行符 '\n'
print a    结果:'hello world.\nit is a nice day.'
 

使用 () 或者 \ 来换行

当代码太长或者为了美观起见时,我们可以使用两种方法来将一行代码转为多行代码:
  • ()
  • \
a = ("hello, world. "
    "it's a nice day. "
    "my name is xxx")
print a    结果:"hello, world. it's a nice day. my name is xxx"
a = "hello, world. " \
    "it's a nice day. " \
    "my name is xxx"
print a    结果:"hello, world. it's a nice day. my name is xxx"
 

强制转换为字符串

  • str(ob)强制将ob转化成字符串。
  • repr(ob)也是强制将ob转化成字符串。
不同点如下:
str(1.1 + 2.2)    结果:'3.3'
repr(1.1 + 2.2)    结果:'3.3000000000000003'
 

整数与不同进制的字符串的转化

可以将整数按照不同进制转化为不同类型的字符串。
十六进制:    hex(255)    结果:'0xff'
八进制:        oct(255)    结果:'0377'
二进制:        bin(255)    结果:'0b11111111'

可以使用 int 将字符串转为整数:
int('23')     结果:23
 
还可以指定按照多少进制来进行转换,最后返回十进制表达的整数:
int('FF', 16)    结果:255
int('377', 8)    结果:255
int('11111111', 2)    结果:255

float 可以将字符串转换为浮点数:
float('3.5')    结果:3.5
 

格式化字符串

Python用字符串的format()方法来格式化字符串。
具体用法如下,字符串中花括号 {} 的部分会被format传入的参数替代,传入的值可以是字符串,也可以是数字或者别的对象。
 
'{} {} {}'.format('a', 'b', 'c')    结果:'a b c'
 
可以用数字指定传入参数的相对位置:
'{2} {1} {0}'.format('a', 'b', 'c')    结果:'c b a'

还可以指定传入参数的名称:
'{color} {n} {x}'.format(n=10, x=1.5, color='blue')    结果:'blue 10 1.5'

可以在一起混用:
'{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')    结果:'blue 10 1.5 foo'

可以用{<field name>:<format>}指定格式:
from math import pi
'{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi)    结果:'foo                 5       6.28'
具体规则与C中相同。
也可以使用旧式的 % 方法进行格式化:
s = "some numbers:"
x = 1.34
y = 2
# 用百分号隔开,括号括起来
t = "%s %f, %d" % (s, x, y)
print t    结果:'some numbers: 1.340000, 2'
 




posted @ 2018-07-24 17:16  含笑半步颠√  阅读(232)  评论(0编辑  收藏  举报