欢迎来到无荨的博客

想一千次,不如去做一次。如果自己不努力,那么这一辈子只可能在原地踏步!

python中字符串常见操作(二)

# 可迭代对象有:字典,列表,元组,字符串,集合

str1 = '192.168.1.1'
str2 = 'as df gh jk'
str3 = '小李子'
str4 = ['aa','bb','cc']
str5 = '$$$192.168.1.1&&&'
str6 = '\t\nmysql\t\n'
b = '='

# .join:把可迭代对象转化为字符串
# 字典只循环key
# 只能合并里边是字符串的可迭代对象

>>> res = ''.join(['1','2','3'])
>>> print(res)
123
>>> res = ''.join({'a':12,'b':22,'c':33})
>>> print(res)
abc
>>> res = ''.join(('1','2','3'))
>>> print(res)
123
>>> res = ''.join([1,2,3])
>>> print(res)
res = ''.join([1,2,3])
TypeError: sequence item 0: expected str instance, int found
>>> res = b.join(str4)
>>> print(res)
aa=bb=cc

# splite:是可以把字符串分割成列表;rsplit

>>> res = str1.split('.',1)
>>> print(res)
['192', '168.1.1']
>>> res = str1.split('.')
>>> print(res)
['192', '168', '1', '1']
>>> res = str2.split('空格')
>>> print(res)
['as', 'df', 'gh', 'jk']

面试题:
test = "aa ks js \t fa \t ka ",除去\t和空格?
result = test.split()

# replace:替换字符串

>>> res = str1.replace('.','|',1)
>>> print(res)
192|168.1.1
>>> res = str1.replace('.','|')
>>> print(res)
192|168|1|1

# strip:去除字符串两边指定字符,(一般用来除去两边特殊字符或格式)
# rstrip(从右边开始),lstrip(从左边开始)

>>> res = str5.strip('$&')
>>> print(res)
192.168.1.1
>>> res = str5.rstrip('$&')
>>> print(res)
$$$192.168.1.1
>>> res = str5.lstrip('$&')
>>> print(res)
192.168.1.1&&&
>>> res = str6.lstrip()
>>> print(res)
mysql

# utf8格式的字符编码:1个中文占3个字节,生僻字会占用更多
# gbk格式的字符编码:1个中文占2个字节
# 用什么字符编码写入就需要用什么字符编码格式打开
#encode和decode分别指编码和解码

>>> res = str1.encode('utf-8')
>>> print(res)
b'$$$192.168.1.1&&&'
>>> res = str6.encode('utf-8')
>>> print(res)
b'\t\nmysql\t\n'
>>> res = str3.encode('utf-8')
>>> print(res)
b'\xe5\xb0\x8f\xe6\x9d\x8e\xe5\xad\x90'
>>> res = str3.encode('utf-8')
>>> result = res.decode('utf-8')
>>> print(result)
小李子

#字符串可以拼接:相加,可以与数字相乘
# a = '123'
# b = 'abc'
# print(a+b)

posted @ 2019-10-11 07:29  无荨  阅读(334)  评论(0编辑  收藏  举报