python中对字符串进行操作

一:字符串的定义方式:

a = 'hello'
b = 'what\'s up'
c = "what's up"
print(a)
print(b)
print(c)

在这里插入图片描述

二:对字符串进行操作

索引:

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

切片:

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

在这里插入图片描述

#显示所有字符
print(s[:])
#显示前3个字符
print(s[:3])
#对字符串倒叙输出
print(s[::-1])
#除了第一个字符以外,其他全部显示
print(s[1:])

在这里插入图片描述

重复:

 print(s * 5)

连接:

print(s + 'world')

在这里插入图片描述

for循环(迭代):

for i in s:
        print(i)

在这里插入图片描述
成员操作符:

print('h' in s)

在这里插入图片描述

扫描二维码关注公众号,回复: 6755405 查看本文章

三:判断字符串里每个元素是什么类型

判断字符串是否为数字,是就返回true,不是就返回False

print('123'.isdigit())
print('123abc'.isdigit())

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

print('Hello'.istitle())
print('HeLlo'.istitle())

判断字符串是否为大写字母

print('hello'.upper())     可以将小写转换为大写
print('hello'.isupper())     判断字符串是否为大写字母

在这里插入图片描述

判断字符串是否为小写字母

print('HELLO'.lower())     可以将大写转换为小写
print('HELLO'.islower())      判断字符串是否为小写字母

判断字符串是否为字母

print('123'.isalpha())
print('aaa'.isalpha())

判断字符串是否是字母或者数字

print('hello123'.isalnum())
print('123'.isalnum())

在这里插入图片描述

四:字符串去除两边空格或者指定字符

In [1]: s = '      hello      '                                         

In [2]: s                                                               
Out[2]: '      hello      '

In [3]: s.strip()                去除两边空格                            
Out[3]: 'hello'

In [4]: s.rstrip()              去除右边空格                   
Out[4]: '      hello'

In [5]: s.lstrip()               去除左边空格                                       
Out[5]: 'hello      '

In [6]: s = '\nhello\t\t'        

In [8]: s = 'helloh'                                                    

In [9]: s.strip('h')              去除字符串里面的全部h                               
Out[9]: 'ello'

In [10]: s.rstrip('h')            去除字符串里面的右边h                            
Out[10]: 'hello'

In [11]: s.lstrip('he')           去除字符串里面的左边he             
Out[11]: 'lloh'

在这里插入图片描述

s = '\nhello\t\t\n'
print(s)
print(s.strip())

在这里插入图片描述

五.字符串的搜索与替换

s = 'hello world hello'

#find找到子串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
#rfind找到子串,并返回最大索引
print(s.rfind('hello'))

#替换字符串中所有的'hello'为'westos'
print(s.replace('hello','westos'))

在这里插入图片描述
字符串的替换:(可以输入你想要替换的语句,以及替换成什么样子)

s  = input("请输入字符:")
h = input("请输入替换字符:")

for i in (s):
    for i in (h):
      s = s.replace(i, "")

print(s)

在这里插入图片描述

六:字符串的对齐

print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'*'))
print('学生管理系统'.ljust(30,'*'))
print('学生管理系统'.rjust(30,'*'))
print('学生管理系统'.rjust(30,'@'))

在这里插入图片描述

七.字符串的统计

print('hello'.count('l'))
print('hello'.count('ll'))
print(len('hello'))

在这里插入图片描述

八:字符串的分离和连接

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

date = '2019-01-15'
date1 = date.split('-')
print(date1)

#通过指定的字符进行连接
print(''.join(date1))
print('/'.join(date1))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/bmengmeng/article/details/94005797