Python学习---字符串操作

时间:2023-03-09 13:30:42
Python学习---字符串操作

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

 str = "Hello World!"
str2 = str[:6] + "tyche !"
print(str2) ===》》》Hello tyche !

###  字符串运算符

 str1 = "hello"
str2 = "world"
print(str1 + str2)
print(str1*2)
'H' in str1
'h' in str1 ===》》》 helloworld
hellohello
False
True

### 字符串格式化输出

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

 ===》》》我叫 小明 今年 10 岁, 今天走了 3.500 Km !

### 多行字符串

 str = '''这是一个
... 多行
... 字符串'''
print(str) ===》》》这是一个
多行
字符串

### 字符串首字母大写

 str = "hello World"
print(str.capitalize()) ===》》》Hello world

(其他的字母小写)

### 字符串居中

 str = "hello World"
str.center(60)
str.center(60, '*') ===》》》' hello world '
'************************hello world*************************'

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

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

### 字符串判断字符

 str = "hello world.txt"
str.endswith("txt")
str.startswith("hello") ===》》》True
True

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

 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False

 isalpha()

如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False isdigit()

如果字符串只包含数字则返回 True 否则返回 False islower()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False isnumeric()

如果字符串中只包含数字字符,则返回 True,否则返回 False isspace()

如果字符串中只包含空白,则返回 True,否则返回 False

### 字符串大小写转换

 lower()
转换字符串中所有大写字符为小写.
upper()
转换字符串中的小写字母为大写