一、字符串
- 轉(zhuǎn)換大小寫
title()
所有單詞首字母大寫
upper()
所有單詞大寫
lower()
所有單詞小寫 - 合并拼接
①用+符號(hào)拼接(效率低)
print('Jim' + 'Green')
JimGreen
②用%符號(hào)拼接
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
- 制表符和換行符
\t tab制表符
\n 換行符
sep為多個(gè)關(guān)鍵字之間的分隔符
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
- 刪除空白
rstrip去除右邊空格
lstrip去除左邊空格
strip去除兩邊空格
first_name = " hello "
print("'"+first_name.rstrip()+"'")
print("'"+first_name.lstrip()+"'")
print("'"+first_name.strip()+"'")
' hello'
'hello '
'hello'
- 添加單雙引號(hào)
first_name = "'hello'"
two_name = '"Python"'
print(first_name)
print(two_name)
'hello'
"Python"
- 字符串轉(zhuǎn)換
ord()函數(shù)獲取字符的整數(shù)表示,chr()函數(shù)把編碼轉(zhuǎn)換為對(duì)應(yīng)的字符
>>>ord('A')
65
>>>ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'文'
python的字符串類型是str,在內(nèi)存中以u(píng)nicode表示,一個(gè)字符對(duì)應(yīng)若干個(gè)字節(jié)。如果在網(wǎng)上傳輸或者保存在磁盤上,就需要把str變成以字節(jié)為單位的bytes。
中文不能轉(zhuǎn)換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)
計(jì)算str包含多少個(gè)字符,可以用len()函數(shù)
>>> len('ABC')
3
>>> len('中文')
2
計(jì)算的是str的字符數(shù),如果換成bytes,len()函數(shù)就計(jì)算字節(jié)數(shù)
>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6