Python学习---字符串操作

### 截取字符串然后拼接

1 str = "Hello World!"
2 str2 = str[:6] + "tyche !"
3 print(str2)
4 
5 ===》》》Hello tyche !

###  字符串运算符

 1 str1 = "hello"
 2 str2 = "world"
 3 print(str1 + str2)
 4 print(str1*2)
 5 'H' in str1
 6 'h' in str1
 7 
 8 ===》》》 helloworld
 9          hellohello
10          False
11          True

### 字符串格式化输出

1 print ("我叫 %s 今年 %d 岁, 今天走了 %.3f Km !" % ('小明', 10, 3.5))
2 
3 ===》》》我叫 小明 今年 10 岁, 今天走了 3.500 Km !

### 多行字符串

1 str = '''这是一个
2 ... 多行
3 ... 字符串'''
4 print(str)
5 
6 ===》》》这是一个 
7         多行
8         字符串

### 字符串首字母大写

1 str = "hello World"
2 print(str.capitalize())
3 
4 ===》》》Hello world

(其他的字母小写)

### 字符串居中

1 str = "hello World"
2 str.center(60)
3 str.center(60, '*')
4 
5 ===》》》'                        hello world                         '
6         '************************hello world*************************'

### 字符串中字符的统计

1 str = "hello World"
2 str.count('l')
3 
4 ===》》》 3

### 字符串判断字符

1 str = "hello world.txt"
2 str.endswith("txt")
3 str.startswith("hello")
4 
5 ===》》》True
6         True

### 判断字符串内容 1 isalnum( 2

 3 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
 4 
 5 isalpha()
 6 
 7 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
 8 
 9 isdigit()
10 
11 如果字符串只包含数字则返回 True 否则返回 False
12 
13 islower()
14 
15 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
16 
17 isnumeric()
18 
19 如果字符串中只包含数字字符,则返回 True,否则返回 False
20 
21 isspace()
22 
23 如果字符串中只包含空白,则返回 True,否则返回 False

### 字符串大小写转换

1 lower()
2 转换字符串中所有大写字符为小写.
3 upper()
4 转换字符串中的小写字母为大写
原文地址:https://www.cnblogs.com/tyche116/p/8717549.html