标签:
字符串 * 数字-------------打印字符串 数字 次
"echo" * 3 ‘echoechoecho‘
字符串相加--------------字符串连在一起
s = ‘hello ‘ + ‘world‘ s ‘hello world‘
字符串长度---------------------len
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 = ‘ ‘ s.join(numbers) ‘1 2 3 4 5‘ s = ‘,‘ s.join(numbers) ‘1,2,3,4,5‘
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(‘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‘
标签:
原文地址:http://www.cnblogs.com/zpython/p/5486588.html