|
5、字符串操作
(一) 创建字符串
str1 = "Hello, EEWorld! This is a Python string."
(二) 连接字符串
str1 = "Hello" + " " + "EEWorld"
print(str1)
# 输出: Hello EEWorld
(三) 裁剪操作
substring = str1[6:12]
print(substring)
# 输出: EEWorld
(四) 查找子字符串
index = str1.find("EEWorld")
print( index)
# 输出: 6
(五) 替换子字符串
replace = str1.replace("EEWorld", "World")
print(replace)
# 输出: Hello, World! This is a Python string.
(六) 分割字符串
split_string = str1.split(" ")
print("Split string:", split_string)
# 输出: [Hello, EEWorld!, 'This', 'is','a','Python','string.']
(七) 大小写转换
lower_string = str1.lower()
upper_string = str1.upper()
print(lower_string)
print(upper_string)
# 输出: [hello, eeworld!, 'this', 'is','a','python','string.']
# 输出: [HELLO, EEWORLD!, 'THIS', 'IS','A','PYTHON','STRING.']
(八) 判断字符串是否以特定子串开始或结束
start = str1.startswith("Hello")
end = str1.endswith("string.")
print(start)
print(end)
# 输出:True
# 输出:True
(九) 判断字符串是否只包含字母或数字
is_alpha = str1.isalpha()
is_num = str1.isnumeric()
print("Is alphabetic:", is_alpha)
print("Is numeric:", is_num)
# 输出:True
# 输出:False