python string

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

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
  • python是用来做什么的
    python是用来做什么的
    08-05
  • python操作excel
    python操作excel
    08-05
  • python用来干什么的
    python用来干什么的
    08-05
  • python语言能做什么
    python语言能做什么
    08-05
  • Python工程师就业前景
    Python工程师就业前景
    08-05
  • python格式化字符串
    python格式化字符串
    08-05
  • python怎么实时监控logstash日志
    python怎么实时监控logstash日志
    08-05
  • python应该怎么学呢
    python应该怎么学呢
    08-05
  • python能做些什么
    python能做些什么
    08-05
  • python xlwt
    python xlwt
    08-05