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

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

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

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

输出结果:

1 helloworld
2 helloworld
3 lloworld
4 hello
5 lowor
6 ld
7 i love you
8 youyouyouyouyou

常用的方法:

 1 str = 'helloword'
 2 str1 = 'HELLOWORD'
 3 str2 = 'HelLOwoRd'
 4 
 5 
 6 print(str.title())
 7 print(str1.title())     # string.title()函数让字符串首字母大写,其他都小写
 8 
 9 print(str.upper())
10 print(str2.upper())     # string.upper()函数使字符串所有字母大写
11 
12 print(str1.lower())
13 print(str2.lower())     # string.lower()函数使字符串所有字母小写

输出结果:

1 Helloword
2 Helloword
3 HELLOWORD
4 HELLOWORD
5 helloword
6 helloword

去除字符串前后的空格:

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

输出结果:

 hello hello   hello 
hellohello
hellohello
hello word

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

 

原文地址:https://www.cnblogs.com/zuoxide/p/10509905.html