010-python基础-数据类型-字符串操作

时间:2023-10-07 18:46:07

1、移除空白

 username.strip()

2、分割

 names = "alex,jack,rain"
names_1 = names.split(",") #  字符串分割之后变成列表
print(names_1)
#输出
['alex', 'jack', 'rain']

3、合并列表各元素成为字符串

 names_1 =  ['alex', 'jack', 'rain']
names_2 = "|".join(names_1)
print(type(names_1))
print(names_2)
# 输出
<class 'list'>
alex|jack|rain
#####
names_1 = "alex"
names = "apple"
names_2 = names.join(names_1)
print(type(names_1))
print(names_2)
#输出
<class 'str'>
aapplelappleeapplex # apple作为分割符,分割names_1的各元素

4、字符串切片

 name = "alexli"
print(name[2:4]) #方法与列表类似
#输出
ex

5、字符串是否是纯数字

 age = input("age:")
print(type(age))
if age.isdigit():   # isdigit()用于判断输入的字符串是否为纯数字,如果是,返回为True
age = int(age)
print(type(age))
else:
print("invaild data type")

6、其他

 name ='alex%sdf'
print(name.isalnum())
print(name.endswith("df"))   #判断字符结尾
print(name.startswith("la"))  #判断字符开始
print(name.upper().lower())
print(len(name))        #判断字符长度
print(name[0])         #根据字符索引进行切片
# 输出
False
True
False
alex%sdf
8
a