将来的你会感谢现在努力的自己,骚年,趁年轻多努力学习 ------ Jasper_boy

python学习之字符串变量

1.字符串引用变量
name="Jasper"
age=23
msg="my name is %s,my age is %s"%(name,age)
print(msg)
View Code

运行结果:
my name is Jasper,my age is 23

除了上面方法可以直接引用 变量,还可以使用format函数

msg="my name is {name},my age is {age}"
msg2=msg.format(name="huqiang",age=23)
print(msg2)
View Code

运行结果:

my name is huqiang,my age is 23

#format还有一种表达形式,使用0,1,2……传参的形式,只能顺序不能跨数字

msg="my name is {0},my age is {1} and {2}"
print(msg.format("huqiang",29,30))
View Code

运行结果:

my name is huqiang,my age is 29 and 30

 

2.字符切片

name="my name is Jasper"
print(name[0:-1:2])
运行结果:
m aei ap
#字符切片同列表一样

切片另一种用法
print(name.center(50,'-'))
运行结果:
----------------my name is Jasper-----------------
#center函数总共50个字符,在字符串两边补全
#find count index用法与列表同样
name="my name is Jasper"
print(name.find("J"))
print(name.count("m"))
print(name.index("a"))

运行结果:

11
2
4


3.字符串判断函数

name="jasp1_er"

print(name.isdigit())
#判断是否数字
print(name.isalnum())
#判断是否有特殊字符
print(name.startswith(name))
#判断开始字符是否一致
print(name.endswith('er'))
#判断结尾字符是否一致
print(name.upper())
#转换大写
运行结果:

False
False
True
True
JASP1_ER



示例:isdigit:是否数字

age=input("age:") if age.isdigit(): age=int(age) print("is int:",age) else: print("invalid data type")


 

posted @ 2016-11-11 14:53  Jasper_boy  阅读(244)  评论(0编辑  收藏  举报