码迷,mamicode.com
首页 > 编程语言 > 详细

python----------字符串

时间:2016-05-13 11:40:55      阅读:459      评论:0      收藏:0      [点我收藏+]

标签:

字符串 * 数字-------------打印字符串 数字 次

"echo" * 3
‘echoechoecho‘

  

字符串相加--------------字符串连在一起

s = ‘hello ‘ + ‘world‘
s
‘hello world‘

字符串长度---------------------len

分割:s.split

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

ine = "1 2 3 4  5"
numbers = line.split()
print numbers
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]

line = "1,2,3,4,5"
numbers = line.split(‘,‘)
print numbers
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]

连接:s.join

s = ‘ ‘
s.join(numbers)
‘1 2 3 4 5‘
s = ‘,‘
s.join(numbers)
‘1,2,3,4,5‘

替换:s.replace

s = "hello world"
s.replace(‘world‘, ‘python‘)
‘hello python‘

大小写转换:

s.upper()方法返回一个将s中的字母全部大写的新字符串。

s.lower()方法返回一个将s中的字母全部小写的新字符串。

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

去除多余空格:

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

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

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

s = "  hello world   "
s.strip()
‘hello world‘

多行字符串:

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

a = """hello world.
it is a nice day."""
print a
hello world.
it is a nice day.

在储存时,我们在两行字符间加上一个换行符 ‘\n‘

使用 () 或者 \ 来换行:

当代码太长或者为了美观起见时,我们可以使用两种方法来将一行代码转为多行代码:

  • ()
  • \
a = ("hello, world. "
    "it‘s a nice day. "
    "my name is xxx")
a
"hello, world. it‘s a nice day. my name is xxx"


a = "hello, world. "     "it‘s a nice day. "     "my name is xxx"
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‘

格式化字符串: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) t ‘some numbers: 1.340000, 2‘

  

 

python----------字符串

标签:

原文地址:http://www.cnblogs.com/zpython/p/5486588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!