一、字符串
- 轉換大小寫
title()
所有單詞首字母大寫
upper()
所有單詞大寫
lower()
所有單詞小寫 - 合并拼接
①用+符號拼接(效率低)
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
- 制表符和換行符
\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
- 刪除空白
rstrip去除右邊空格
lstrip去除左邊空格
strip去除兩邊空格
first_name = " hello "
print("'"+first_name.rstrip()+"'")
print("'"+first_name.lstrip()+"'")
print("'"+first_name.strip()+"'")
' hello'
'hello '
'hello'
- 添加單雙引號
first_name = "'hello'"
two_name = '"Python"'
print(first_name)
print(two_name)
'hello'
"Python"
- 字符串轉換
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