當前位置:科普知識站>IT科技>

python|string

IT科技 閲讀(2.46W)

1、string簡介:

string就是字符串,字符串是Python中最長用的數據類型,可以使用引號('或")來創建字符串。事實上,在Python中,加了引號的字符都被認為是字符串。

name = "Changsh" #雙引號

age ="5000" #只要加雙引號就是字符串

age_1 =5000 #不加,整形

msg ="""I'm in Changsha"""#三雙引號

msg_1 ='''I' m in Hengyang'''#三單引號

hometowm ='Changsha' #單引號

print(type(name),type(age),type(age_1),type(msg),type(msg_1),type(hometown),sep="|")

python string

2、字符串運算及操作:

拼接:

>>> a="Hello"

>>> b="Python"

>>> a+b

'HelloPython'

注意,字符串的拼接只能是對方都是字符串,不能跟數字或其它類型拼接。

>>>age_1=5000

>>>name+age_1

Traceback (most recent call last): 

File"<stdin>",line 1,in <module>

TypeError:must be str,not int

重複:

>>> a="Hello"

>>> a*3

'HelloHelloHello'

字符串索引:

#########0123456789012345367890123456789

>>> a = "Life is short,I use python"

>>>len(a)

27

>>> #索引

>>>a[0]

'L'

>>>a[-1]

'n'

>>> #切片

...

>>> a[:13] #從第一個元素開始,一直到索引值為12的元素

'Life is short'

>>> a[15:] #從索引值為15的元素開始,一直到最後

'I use python'

>>> a[15::2] #從索引值為15的元素開始,步長為2,即每次跳過一個元素,一直到最後

'Iuepto'

>>> a[::-1] #逆序輸出

'nohtyp esu I ,trohs si efiL'

python string 第2張

大小寫轉換:

str.lower():轉小寫

str.upper():轉大寫

str.swapcase():大小寫對換

str.capitalize():字符串首為大寫,其餘小寫

str.title():以分隔符為標記,首字符為大寫,其餘為小寫

>>> a="Life is short, I use python"

>>> a.lower() #將所有大寫字符轉換為小寫字符

'life is short, i use python'

>>> a.upper() #將所有小寫字符轉換為大寫字符

'LIFE IS SHORT, I USE PYTHON'

>>> a.swapcase() #將大小寫互換

'lIFE IS SHORT, i USE PYTHON'

>>> a.capitalize() #將首字符大寫

'Life is short, i use python'

>>> a.title() #返回標題化的字符串

'Life Is Short, I Use Python'

>>>

字符串格式輸出對齊:

str.center()居中

str.ljust()左居中

str.rjust()右居中

str.zfill()左居中,以0填充長度

python string 第3張

刪除指定參數:

str.lstrip()

str.rstrip()

str.strip()

計數:

Excel表格中:

=COUNTIF(B2:B31,">=30")/COUNT(B2:B31)

字符串條件判斷:

isalnum(),字符串由字母或數字組成,

isalpha(),字符串只由字母組成,

isdigit(),字符串只由數字組成