——————–数据格式化—————————-
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 格式化字符串
str1 = "version"
num = 1.0
format = "%s" % str1
print format
format = "%s %d" % (str1, num)
print format
# 带精度的格式化
print "浮点型数字: %f" % 1.25
print "浮点型数字: %.1f" % 1.25
print "浮点型数字: %.2f" % 1.254
# 使用字典格式化字符串
print "%(version)s: %(num).1f" % {"version": "version", "num": 2}
# 字符串对齐
word = "version3.0"
print word.center(20)
print word.center(20, "*")
print word.ljust(0)
print word.rjust(20)
print "%30s" % word
#输出
>>>
version
version 1
浮点型数字: 1.250000
浮点型数字: 1.2
浮点型数字: 1.25
version: 2.0
version3.0
*****version3.0*****
version3.0
version3.0
version3.0
>>>
——————-转义字符———————
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 输出转义字符
path = "hello\tworld\n"
print path
print len(path)
path = r"hello\tworld\n"
print path
print len(path)
# strip()去掉转义字符
word = "\thello world\n"
print "直接输出:", word
print "strip()后输出:", word.strip()
print "lstrip()后输出:", word.lstrip()
print "rstrip()后输出:", word.rstrip()
#输出
>>>
hello world
12
hello\tworld\n
14
直接输出: hello world
strip()后输出: hello world
lstrip()后输出: hello world
rstrip()后输出: hello world
>>>
—————–连接字符—————————
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用"+"连接字符串
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print result
# 使用join()连接字符串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print result
# 使用reduce()连接字符串
import operator
strs = ["hello ", "world ", "hello ", "China "]
result = reduce(operator.add, strs, "")
print result
#输出
>>>
hello world hello China
hello world hello China
hello world hello China
>>>
——————字符串操作函数———————–
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用索引截取子串
word = "world"
print word[4]
# 使用split()获取子串
sentence = "Bob said: 1, 2, 3, 4"
print "使用空格取子串:", sentence.split()
print "使用逗号取子串:", sentence.split(",")
print "使用两个逗号取子串:", sentence.split(",", 2)
# 字符串连接后将分配新的空间
str1 = "a"
print id(str1)
print id(str1 + "b")
# 特殊切片截取子串
str1 = "hello world"
print word[0:3]
print str1[::2]
print str1[1::2]
#输出
>>>
d
使用空格取子串: ['Bob', 'said:', '1,', '2,', '3,', '4']
使用逗号取子串: ['Bob said: 1', ' 2', ' 3', ' 4']
使用两个逗号取子串: ['Bob said: 1', ' 2', ' 3, 4']
41185408
46365832
wor
hlowrd
el ol
>>>
startswith()函数判断文本是否以某个字符开始,
endswith()函数判断文本是否以某个字符结束。
—————–字符串反转————————-
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用list的reverse()
def reverse(s):
li = list(s)
li.reverse()
s = "".join(li)
return s
print reverse("hello")
# 循环输出反转的字符串
def reverse(s):
out = ""
li = list(s)
for i in range(len(li), 0, -1):
out += "".join(li[i-1])
return out
print reverse("hello")
# 特殊切片反转字符串
def reverse(s):
return s[::-1]
print reverse("hello")
#输出
>>>
olleh
olleh
olleh
>>>