预留广告位
预留广告位
预留广告位
当前位置:首页  »  科技  »  科技百科  »  文章  »  python string

python string

来源:网络 转载:好巧合 时间:2022-01-22 21:30
导读python string,1、string简介:string就是字符串,字符串是Python中最长用的数据类型,可以使用引号('或")来创建字符串。事实上,在Python中,加了引号的字符都被认为是字符串。2、字符串运算及操作:拼接:a=“Hello”;b=“Python”。

python中string是什么,怎么使用呢?不知道的小伙伴来看看小编今天的分享吧!

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="|")

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'

大小写转换:

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填充长度

删除指定参数:

str.lstrip()

str.rstrip()

str.strip()

计数:

Excel表格中:

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

字符串条件判断:

isalnum(),字符串由字母或数字组成,

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

isdigit(),字符串只由数字组成

以上就是小编今天的分享了,希望可以帮助到大家。

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。

预留广告位
标签:python  string  
Top