python_11(format、转义字符、连接字符、字符串操作函数、字符串反转)

来源:互联网 发布:上海ug编程培训 编辑:程序博客网 时间:2024/05/16 05:20

——————–数据格式化—————————-

#!/usr/bin/python# -*- coding: UTF-8 -*-# 格式化字符串str1 = "version"num = 1.0format = "%s" % str1print formatformat = "%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#输出>>> versionversion 1浮点型数字: 1.250000浮点型数字: 1.2浮点型数字: 1.25version: 2.0     version3.0     *****version3.0*****version3.0          version3.0                    version3.0>>> 

——————-转义字符———————

#!/usr/bin/python# -*- coding: UTF-8 -*-# 输出转义字符path = "hello\tworld\n"print pathprint len(path)  path = r"hello\tworld\n" print pathprint len(path)  # strip()去掉转义字符word = "\thello world\n"print "直接输出:", wordprint "strip()后输出:", word.strip()print "lstrip()后输出:", word.lstrip()print "rstrip()后输出:", word.rstrip()#输出>>> hello   world12hello\tworld\n14直接输出:   hello worldstrip()后输出: hello worldlstrip()后输出: hello worldrstrip()后输出:    hello world>>> 

—————–连接字符—————————

#!/usr/bin/python# -*- coding: UTF-8 -*-# 使用"+"连接字符串str1 = "hello "str2 = "world "str3 = "hello "str4 = "China "result = str1 + str2 + str3result += str4print result# 使用join()连接字符串strs = ["hello ", "world ", "hello ", "China "]result = "".join(strs)print result# 使用reduce()连接字符串import operatorstrs = ["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']4118540846365832worhlowrdel ol>>> 
startswith()函数判断文本是否以某个字符开始,endswith()函数判断文本是否以某个字符结束。

—————–字符串反转————————-

#!/usr/bin/python# -*- coding: UTF-8 -*-# 使用list的reverse()def reverse(s):        li = list(s)     li.reverse()    s = "".join(li)    return sprint reverse("hello")# 循环输出反转的字符串def reverse(s):    out = ""    li = list(s)     for i in range(len(li), 0, -1):        out += "".join(li[i-1])    return outprint reverse("hello")# 特殊切片反转字符串def reverse(s):    return s[::-1]print reverse("hello")#输出>>> olleholleholleh>>> 
0 0
原创粉丝点击