Python(一)字符串基本操作

一、去除字符串空格

s = '   abcf hgklj  '
s.strip() // 去除左右空格
s.lstrip() //去除左空格
s.rstrip() //去除右空格

二、字符串连接

s1 = 'abc'
s2 = 'def'
s1+s2

三、大小写

s = 'avc def'
s.upper() 全部改成大写
s.lower() 全部改成小写
s.capitalize() 首字母大写

四、位置比较

s_1 = 'abcdefg'
s_2 = 'abdeffxx'
print(s_1.index('bcd'))
print(s_2.index('bcd'))//异常 因为s_2中没有bcd

五、捕获异常

try:
    print(s_2.index('bcd'))
except ValueError:
    pass //忽略异常

六、比较
//python3里面cmp函数被移除

print(s_1 == s_2)
print(s_1 < s_2)
print(s_1 > s_2)

七、求长度

len('abc')

八、空字符串相当于false

s = ' '
if not s:
    print('Empty')

九、字符分割与连接

s = 'abc,def,ghi'
splitted = s.split(',')
print(type(splitted)) //输出list
print(splitted)//输出['abc','def','ghi']

按行分割字符

s = """abc
def
ghi"""
s_1 = s.split('\n')//第一种方法
s_2 = s.splitlines() //第二种方法

连接

s = ['abc','def','ghi']
print(''.join(s))//输出abcdefghi
print('-'.join(s))//输出abc-def-ghi
print('\n'.join(s))//输出abc
                         def
                         ghi

十、字符串常用判断
startswith()
判断字符串是否以某个字符开头

s = 'abcdefg'
print(s.startswith('abc'))//返回True
print(s.endswith('efg')
//其他的一些判断用法
print('123456abcd'.isalnum())
print('\t12ab'.islanum())
print('abcd'.isalpha())
print('1234'.isdigit())
print('    '.isspace())
print('abcd1234'.islower())
print('abcd1234'.isupper())
print('Hello World'.istitle())

十一、字符串与数字之间的转换

数字到字符串的转化
print(str(5))
print(str(5.))//后面自动补0
print(str(-5.23))
字符串到数字
print(int('1234'))
print(float('1234.34'))
二进制转换为十进制
print(int('110111',2))
十六进制转化为十进制
print(int('ffff',16))

十二、字符串不可修改,将字符串放到一个数组里面去

s = 'abcdefg'
l = list(s)
print(l)

猜你喜欢

转载自blog.csdn.net/Missayaaa/article/details/80029552