python中的字符处理

1)字符串的定义方式

三种定义方式:

1 变量名  = "字符串"

2 变量名  = '字符串'

3" " "

多个字符串

 " " "

a='hello'  #定义一个字符串hello
b="word"   #定义一个字符串word
c="""      """定义多个字符串"""
hello
word
"""

2)字符串的替换和索引

1. 索引:0,1,2,3,4 索引值是从0开始

s='hello'
print s[0]
print s[1]


2.len()的用法

s='hello world'
print len(s) #查看s变量里面的字符数

可以看出len的查看字符数包括空格!

3. find()找到字符串 并返回最小的索引

    find()方法判断字符串str,如果起始索引beg和结束end索引能找到在字符串或字符串的一个子串中。

find()方法的语法:str.find(str, beg=0 end=len(string))参数     str -- 此选项指定要搜索的字符串。     beg -- 这是开始索引... 
s='hello world'
print s.find('hello')   #返回值为0   
print s.find('world')   #返回值为6     
print s.replace('hello','like')   #将'hello'替换成'like'



##从结果来看第一个返回值为0,第二个为6。说明第一次find(0)代表是'hello'这个字符串,而检索第二个字符串时则是以计数前面的字符'h','e','l','l','o','' 

3)字符串的特性

# 切片
print s[0:3]  # 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step

#显示方式的不同

s='hello world'
print s[0:4:2],   //加','表示不换行
print s[0:4]

**************
print s[0:4:2]    //不加','表示换行
print s[0:4]


# 显示所有字符

s='good boy'
print s[:]


# 显示前3个字符

s='good boy'
print s[:3]


# 对字符串倒叙输出

s='good boy'
print s[::-1]


# 除了第一个字符以外,其他全部显示

s='good boy'
print s[1:]

# 重复

s='skr!'
print s * 10

# 连接

print 'hello ' + 'world'+s

# 成员操作符

s='hello world'
print 'q' in s
print 'he' in s

s='hello haha'
print 'aa' in  s    #s这个字符串中虽然有两个a但是不是连着出现的,所以返回False

4)字符串的统计

print 'helloooo'.count('o')

5)字符串判断是否大小写或数字

# 判断字符串里面的每个元素是什么类型
# 一旦有一个元素不满足,就返回False

s='123'
print '123'.isdigit()    判断是否为数字,输出结果为True
print '123abc'.isdigit()  输出结果为False

# title:标题 判断某个字符串是否为标题(第一个首字母大写,其余字母小写)

print 'Hello'.istitle()  返回值为True
print 'HeLlo'.istitle()  返回值为False

print 'hello'.upper()  将每个字符都换成大写
print 'hello'.islower()  判断每个字符是否为小写
print 'HELLO'.lower() 将每个字符都换成小写
print 'HELLO'.isupper() 判断每个字符是否为大写
print 'hello'.isalnum()     判断是否为数字和字母组成的字符串 (有一个不是就返回False)
print '123'.isalpha()   判断每个字符是否为数字

6)字符串的开头和结尾匹配

s = 'hello.jpg'
print s.endswith('.png')找到.png结尾i的字符串,返回值为False

url1 = 'http://www.baidu.com' 
url2 = 'file:///mnt'

print url1.startswith('http://') 找到以http://开头的字符号 返回值为True
print url2.startswith('f')  返回值为False

7)字符串的分离和连接

#分离   将字符串以分割符为单位进行分离

# split对于字符串进行分离,分割符为'.'
s = '172.25.254.250'
s1 = s.split('.')
print s1

date = '2018-8-27'
date1 = date.split('-')
print date1


# 连接

print ''.join(date1)    理解为把date1里面的分割符以空代替输出
print '/'.join(date1)   理解为把date1里面的分隔符以/代替输出
print '/'.join('time')  理解为在time这个字符串中每个字符之间加入/

猜你喜欢

转载自blog.csdn.net/yangkaiorange/article/details/82148617
今日推荐