当前位置:科普知识站>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(),字符串只由数字组成