- 在python中,字符串的類型是不支持修改的
如在編譯器中使用如下代碼:
import string
x = 'abcd'
x[0] = 'p'
將出現(xiàn)錯誤:
x[0] = 'p'
TypeError: 'str' object does not support item assignment
- 去除空格
s = " 111 222 333 "
print(s) # 原本的字符串
print(s.strip()) # 刪除左邊和右邊的空格
print(s.lstrip()) # 刪除左邊的空格
print(s.rstrip()) # 刪除右邊的空格
print(s) # 觀察去除空格后的字符串
111 222 333
111 222 333
111 222 333
111 222 333
111 222 333
注意:由于字符串本身并不能被修改,所以去除空格后打印出變量s仍然沒有改變
- 大小寫的轉(zhuǎn)換
s = 'hello world'
print(s.upper()) # 所有字母大寫
print(s.upper().lower()) # 所有字母小寫
print(s.capitalize()) # 首字母大寫
HELLO WORLD
hello world
Hello world
- 字符串比較
s1 = 'abcdefg'
s2 = 'abcdefh'
print(s1 == s2) # 比較兩個字符串是否一樣
print(s1.index('abc')) # 查看‘a(chǎn)bc’在字符串所在的位置
False
0
注意:對于空的字符串,它與False 是等價的,但是對于None 是一個空指針,與空字符串不一樣,不在內(nèi)存分配一個空間,例如:
s = ''
if not s:
print('empty')
結(jié)果將打印出empty
- 字符串的分割
s = 'abc,def,qqq'
print(s.split(','))
s1 = '''111
222
333
'''
print(s1.splitlines()) # 根據(jù)換行符進(jìn)行分割
['abc', 'def', 'qqq']
['111', '222', '333']
- 字符串的連接
s = ['abc', 'def', 'ggg']
print(''.join(s)) # 可以指定連接符。如,空格,加號等
print('+'.join(s))
abcdefggg
abc+def+ggg
- 其他常用的字符串判斷
str.startswith(prefix) # 是否以prefix開頭
str.endswith(suffix) #是否以suffix結(jié)尾
str.isalnum() # 是否全是字母和數(shù)字,并至少有一個字符。
str.isalpha() # 是否全是字母,并至少有一個字符。
str.isdigit() # 是否全是數(shù)字,并至少有一個字符。
str.isspace() # 是否全是空白字符,并至少有一個字符。
str.islower() # 字母是否全是小寫
str.isupper() # 字母是否全是大寫
str.istitle() # 首字母是否大寫
- 字符串與數(shù)字的相互轉(zhuǎn)化
print(str(5.)) # 將數(shù)字轉(zhuǎn)化為字符串
print(str(66666))
print(str(6.789456))
print(int('444')) # 將字符串轉(zhuǎn)化為數(shù)字
print(int('11111111', 2)) # 將字符串按照指定的進(jìn)制轉(zhuǎn)換為10進(jìn)制
print(float('444.23'))
5.0
66666
6.789456
444
255
444.23