字符串(string)的常用语法和常用函数

时间:2023-03-08 20:22:56

在python中,加了引号(单引号、双引号、三引号)的字符就是字符串类型,python并没有字符类型。

字符串也是很常用的数据类型,这里介绍一些用的较多的语法和方法,直接以代码示例展示。

 str = 'helloworld'
str1 = 'i'
str2 = 'love'
str3 = 'you'
print(str)
print(str[:])
print(str[2:]) # 字符串下标是从0开始记,所以下标2对应hello的第一个l
print(str[:5]) # 会截取从0位到(5-1)位
print(str[3:8]) # 下标3对应hello的第二个l,而后一位数对应(8-1)位是r
print(str[-2:])    # 索引可以是负数,意味着从后往前数
print(str1 + " " + str2 + " " + str3) # 字符串拼接
print(str3*5) # 相当于字符串的快速复制

输出结果:

 helloworld
helloworld
lloworld
hello
lowor
ld
i love you
youyouyouyouyou

常用的方法:

 str = 'helloword'
str1 = 'HELLOWORD'
str2 = 'HelLOwoRd' print(str.title())
print(str1.title()) # string.title()函数让字符串首字母大写,其他都小写 print(str.upper())
print(str2.upper()) # string.upper()函数使字符串所有字母大写 print(str1.lower())
print(str2.lower()) # string.lower()函数使字符串所有字母小写

输出结果:

 Helloword
Helloword
HELLOWORD
HELLOWORD
helloword
helloword

去除字符串前后的空格:

 str3 = ' hello'
str4 = 'hello '
str5 = ' hello '
str6 = "hello word" print(str3, end=" ")
print(str4, end=" ")
print(str5) # 显示各自输出字符串,为了方便观察,让三个字符串输出在一行
print(str3.lstrip(), end="") # 去除字符串左边或前边的空格
print(str4.rstrip()) # 去除字符串右边或后边的空格
print(str5.strip(), end="") # 去除字符串前后的空格
print(str3.strip()) # 不能去除字符串中间的空格,因为这种空格也属于字符串本身内容的一部分
print(str6.strip())

输出结果:

 hello hello   hello
hellohello
hellohello
hello word

关于字符串的使用方法还有很多,刚开始学时也不可能都去学,只能是先学一些常用的,然后在以后的深入学习中遇到了再去学,或者需要了再去学。

相关文章