Python基础学习----字符串处理

关注公众号“码农帮派”,查看更多系列技术文章:

 

1.字符串处理

(1-1)字符串的格式化

Python中可以使用%进行字符串的格式化:

【说明】%f可以对浮点数进行格式化,可以指定格式化的精度,Python会根据制定的精度进行“四舍五入":

Python常用的格式化字符串替代符

 

符号说明
%c格式化字符及其ASCII码
%s格式化字符串
%d格式化整数
%u格式化无符号整数
%o格式化无符号八进制数
%x格式化无符号十六进制数
%X格式化无符号十六进制数(大写)
%f格式化浮点数
%e使用科学计数法格式化浮点数
%E作用在%e,用科学计数法格式化浮点数
%g根据值的大小决定使用%f还是%e
%G作用在%g,根据值的大小决定使用%f还是%e
%p用十六进制数格式化变量的地址

 

可以只用字典格式化字符串:

 

 

#coding=utf-8
content = "%(str)s : %(num).1f" % {"str": "version", "num": 1.2}
print content

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
version : 1.2

Process finished with exit code 0

 

 

 

我们还可以使用center(),just()对字符串进行对其操作:

 

str = "helloWorld"
# 字符串放在20个单位的中间位置
print str.center(20)
# 字符串位于中间,左右空白处使用*填充
print str.center(20, "*")
# 左对齐,整体占20个单位位置
print str.ljust(20)
# 右对齐,整体占20个单位的位置
print str.rjust(20)
# 也可以使用%方法进行对其操作,对其方式是左对齐,类似rjust()
print "%20s" % str

打印结果:

 

 

/ usr / bin / python2.7 / home / mxd / 文档 / WorkPlace / python / PythonStudy / test.py
helloWorld
** ** *helloWorld ** ** *
helloWorld
helloWorld
helloWorld

Process
finished
with exit code 0

 

 

 

(1-2)字符串的转义

Python中使用"\"进行字符的转义,转义后的字符,"\t"或者"\n"均只占一个字符的位置。

 

# coding=utf-8
str = "hello\tworld\t"
print str
print len(str)
# 若要直接打印出转义字符,可以使用自然字符串
rStr = r"hello\nworld\t"
print rStr
print len(rStr)

 

打印结果:

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
hello  world  
12
hello\nworld\t
14

Process finished with exit code 0

 

 

 

Python中常用的转移字符

 

符号说明
\'单引号,为了打印单引号
\"双引号,为了打印双引号
\a播放系统响铃声音
\b退格符
\n换行符
\t制表符
\v回车符
\r回车符
\f换页符
\o八进制代表的字符
\x十六进制代表的字符
\000终止符

 

(1-3)字符串的合并

 

【说明】Python可以使用"+"来连接字符串,但是当"+"号两侧都是数字,则进行加法运算;"+"号两侧都是字符串的时候,则进行字符串连接运算;"+"两侧数据类型不一致的时候,Python会抛出异常。

 

str_1 = "Hello\t"
str_2 = "World,\t"
str_3 = "Hello\t"
str_4 = "Hust"
result = str_1 + str_2 + str_3
result += str_4

print result

 

打印结果:

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
Hello  World,  Hello  Hust

Process finished with exit code 0

 

Python中提供了join()函数,用于连接序列中的字符串,并返回最终的结果:

 

strs = ["Hello\t", "World,\t", "Hello\t", "Hust"]
result = "".join(strs)

print result

 

打印结果相同。

Python的内建函数reduce(func, seq, initival)可以利用函数func对序列seq中的元素进行累计运算,可以通过reduce进行字符串的连接。

 

# coding=utf-8
import operator
# operator模块中的add函数实现两个字符串的"+"操作
strs = ["Hello\t", "World,\t", "Hello\t", "Hust"]
result = reduce(operator.add, strs, "")

print result

打印结果相同。

(1-4)字符串的截取

使用索引,string[index],可以获得字符串中index位置上的字符:

通过切片,string[start : end : step],可以获得字符串中从start位置,到end-1位置上的子字符串,步长为step截取。

可以使用split([char], [num])进行字符串的分割,split()函数中,默认的char为空格,即split()不传入任何参数,split()会按照空格来分割字符串:

 

str = "a,b,c,d,e,f"

result_1 = str.split()
print result_1, len(result_1)

result_2 = str.split(",")
print result_2, len(result_2)

result_3 = str.split(",", 3)
print result_3, len(result_3)

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
['a,b,c,d,e,f'] 1
['a', 'b', 'c', 'd', 'e', 'f'] 6
['a', 'b', 'c', 'd,e,f'] 4

Process finished with exit code 0

(1-5)字符串的比较

 

Python中使用"==" 和 "!=" 来比较两个字符串的内容是否相同。

 

str_1 = "helloWorld"
str_2 = "HelloWorld"
str_3 = "helloWorld"

print str_1 == str_2
print str_1 == str_3

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
False
True

Process finished with exit code 0

 

startswith(substring, [start, [end]]) 函数可以用来匹配字符串开头是否包含特定的子字符串,substring是要进行比较的子字符串,start表示开始比较的位置,end表示比较结束的位置,在[start: end]之间的位置搜索substring,若包含则返回True,否则返回False:

 

# coding=utf-8
str = "hello,World!Hello,Hust!"

print str.startswith('hello')   # result = True
print str.startswith('World', 5, len(str))   # result = False
print str.startswith('World', 6, len(str))   # result = True
print str.startswith('World!', 6)   # result = True

与startswith()相似的函数endswith(substring, [start, [end]])用来匹配字符串结尾处是否包含特定的子字符串,不同的是,endswith()是从字符串的尾部开始搜索。

 

 

# coding=utf-8
str = "hello,World!Hello,Hust!"

print str.endswith("Hust")    # result = False
print str.endswith("Hust!")    # result = True
print str.endswith("!Hello", 0, 17)    # result = True
print str.endswith('Hello', -len(str), -6)    # result = True

(1-6)字符串的反转

Python中没有提供现成的字符串反转的方法,需要自己写,可以使用一下的方法,对字符串进行反转:

【方法一】

 

#coding=utf-8
def reverse(s):
    out = ""
    for i in range(len(s) - 1, -1, -1):
        out += s[i]
    return out

print reverse('HelloWorld')

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
dlroWolleH

Process finished with exit code 0

 

【方法二】

Python中虽然没有提供字符串的反转方法,但是提供了列表的反转方法list.reverse(),可以使用该方法辅助完成列表的反转:

 

#coding=utf-8
def reverse(s):
    tmp = list(s) # 将字符串转化为list
    tmp.reverse() # 调用list的reverse()方法,实现list元素的反转
    result = "".join(tmp)
    return result

print reverse('HelloWorld')

 

 

【方法三】

 

#coding=utf-8
def reverse(s):
    return s[::-1]

print reverse('HelloWorld')

 

 

 

(1-7)字符串的查找和替换

(1-7-1)查找

Python中提供了find(substring, [start, [end]])函数进行子字符串的查找,substring表示待查找的子字符串,[start : end]表示查询的范围:

 

#coding=utf-8
str = 'Hello,World!Hello,Hust!'

print str.find('Hust') # 返回差找到的子字符串的首下标  打印: 18
print str.find('Hust', 12) # 从原字符串的12下标开始查询,打印: 18
print str.find('Hust', 0, 10) # 没有差找到结果,打印: -1
print str.find('World', 12) # 从原字符串下标12开始查找,未找到,打印: -1

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
18
18
-1
-1

Process finished with exit code 0

 

【说明】find()是从字符串的开头开始向后索引直到差找到substring,rfind(substring, [start, [end]])和find()相似,不同的是rfind()函数是从后向前索引的。

(1-7-2)替换

Python提供了replace(old, new, [max])用来将原字符串中,子字符串old,使用new替换,max表示替换的次数,默认的max应该是Int.MAX_VALUE,会将原字符串中所有的old都替换成new:

 

#coding=utf-8
str = 'HIaaaaHIdddHIssssHIqqHqqHI'
print str.replace('HI', '') # 将str中的'HI'全部替换成''
print str.replace('HI', '', 2) # 只替换str中前两个'HI'为''

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
aaaadddssssqqHqq
aaaadddHIssssHIqqHqqHI

Process finished with exit code 0

 

(1-8)字符串与日期的转换

 

Python中提供了time模块来处理时间,通过time.localtime()可以获得一个当前时间的struct,可以直接从返回的这个struct中获得年月日相关的信息,也可以通过strftime()以及strptime()函数进行时间和字符串之间的转换操作。

 

#coding=utf-8
import time

_time = time.localtime() # 获得当前时间的struct结构体
print _time

print "{0}年{1}月{2}日 {3}时:{4}分:{5}秒".format(_time.tm_year, _time.tm_mon, _time.tm_mday, _time.tm_hour, _time.tm_min, _time.tm_sec)

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
time.struct_time(tm_year=2016, tm_mon=10, tm_mday=14, tm_hour=13, tm_min=51, tm_sec=13, tm_wday=4, tm_yday=288, tm_isdst=0)
2016年10月14日 13时:51分:13秒

Process finished with exit code 0

 

(1-8-1)时间转换为字符串

time模块中可以使用strftime(format, [tuple]) -> string函数,将时间转换成指定format格式的字符串,tuple是一个元组,用来存储需要转换的时间。

 

#coding=utf-8
import time
str_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print str_time
stamp = time.strftime('%s', time.localtime()) # format = '%s',可以获得当前的时间戳(精度秒)
print stamp

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
2016-10-14 13:59:40
1476424780

Process finished with exit code 0

 

(1-8-2)字符串转换为时间

time模块中提供了strptime(string, format) -> struct_time函数,可以将string按照format格式转换成一个time结构体。

 

#coding=utf-8
import time

str = "2016-12-31 12:20:30"
_format = '%Y-%m-%d %H:%M:%S'
struct_time = time.strptime(str, _format)

print struct_time

 

打印结果:

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=31, tm_hour=12, tm_min=20, tm_sec=30, tm_wday=5, tm_yday=366, tm_isdst=-1)

Process finished with exit code 0

 

 

 

格式化时间的常用的标志

 

符号说明
%a英文星期的简写
%A英文星期的全称
%b英文月份的简写
%B英文月份的全称
%c显示本地的日期和时间
%s当前时间对应的时间戳
%S秒数,在01-59之间
%d日期数,取值在1-31之间
%H小时数,取值在00-23之间
%I小时数,取值在01-12之间
%m月份,取值在01-12之间
%M分钟数,取值在01-59之间
%j显示从本年第一天开始,到今天的天数
%w显示今天是星期几,0表示星期日
%W显示今天属于今年的第几周,星期一作为一周的第一天进行计算
%x本地的今天的日期
%X本地的今天的时间
%y年份,取值在00-99之间
%Y年份完整的数字

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值