一、字符串

2017-03-23  本文已影响6人  解脱了

一、字符串

  1. 转换大小写
    title()所有单词首字母大写
    upper()所有单词大写
    lower()所有单词小写
  2. 合并拼接
    ①用+符号拼接(效率低)
print('Jim' + 'Green')
JimGreen

②用%符号拼接

print('%s, %s' % ('Jim', 'Green'))
Jim, Green

③用,或者空白分隔

print('Jim','Green')
print('Jim''Green')
print('Jim'  'Green')
Jim Green
JimGreen
JimGreen

④用join()方法拼接

var_list = ['tom', 'david', 'john']
a = '###'
print(a.join(var_list))
tom###david###john

⑤用format()方法拼接

fruit1 = 'apples'
fruit2 = 'bananas'
fruit3 = 'pears'
str = 'There are {}, {}, {} on the table'
print(str.format(fruit1,fruit2,fruit3))

⑥不常用,字符串乘法

a = 'abc'
print(a * 3)
abcabcabc
  1. 制表符和换行符
    \t tab制表符
    \n 换行符
    sep为多个关键字之间的分隔符
first_name = "hello"
two_name = "Python"
last_name = "world"
print(first_name,two_name,last_name,sep='\t')
print(first_name,two_name,last_name,sep='\n')
hello   Python  world
hello
Python
world
  1. 删除空白
    rstrip去除右边空格
    lstrip去除左边空格
    strip去除两边空格
first_name = " hello "
print("'"+first_name.rstrip()+"'")
print("'"+first_name.lstrip()+"'")
print("'"+first_name.strip()+"'")
' hello'
'hello '
'hello'
  1. 添加单双引号
first_name = "'hello'"
two_name = '"Python"'
print(first_name)
print(two_name)
'hello'
"Python"
  1. 字符串转换
    ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符
>>>ord('A')
65
>>>ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'文'

python的字符串类型是str,在内存中以unicode表示,一个字符对应若干个字节。如果在网上传输或者保存在磁盘上,就需要把str变成以字节为单位的bytes。
中文不能转换ascii

>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

计算str包含多少个字符,可以用len()函数

>>> len('ABC')
3
>>> len('中文')
2

计算的是str的字符数,如果换成bytes,len()函数就计算字节数

>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6
上一篇下一篇

猜你喜欢

热点阅读