人话学Python-基础篇-字符串

        一:字符串的定义

        在Python中使用引号来定义。不论是单引号还是双引号。

str1 = 'Hello World'
str2 = "Hello World"

        二:字符串的访问

        如果我们要取出字符串中单独的字符,需要使用方括号来表示取得的位置。如果要取出字符串的子串,就需要用到冒号表达式

        str[a:b]

        上面的冒号表达式意为从字符串的第a+1位取到第b位

        需要注意的是,和大部分编程语言一样,Python也是从0开始计数。

str = "Hello World"

print("the first string of str is", str[0])
print("the second string of str is", str[1])

print("the first four string of str is", str[0:4])

#>>>the first string of str is H
#>>>the second string of str is e
#>>>the first four string of str is Hell

        使用冒号表达式,可以实现指定位置的字符串替换

str = "Hello World"

print("The new string is", str[:6] + "Bye Bye")

#>>>The new string is Hello Bye Bye

        三:字符串的运算

+字符串连接
*字符串重复输出
in

成员运算符

如果字符串包含给定字符返回1

not in

成员运算符

如果字符串不包含给定字符返回1

%格式字符串
str1 = "Hello"
str2 = "World"

print(str1 + str2)
print(str1*2,str2*3)

print("H" in str1)
print("a" not in str2)

#>>>HelloWorld
#>>>HelloHello WorldWorldWorld
#>>>True
#>>>True

        四:格式字符串     

        格式字符串是一种C语言风格的字符串表示方法,使用%作为标志。

%c格式化字符及ASCII码
%s格式化字符串
%d格式化整数
%f格式化浮点数,可指定精确度
print("My name is %s , I'm %d years old" % ("Jujube" , 19))

#>>>My name is Jujube , I'm 19 years old

        在使用格式化字符串时,有辅助指令可以帮助具体操作。

*定义小数点精度
-左对齐
+在正数前面显示正号
<sp>在正数前面显示空格
0显示的数字前面填充0而不是默认的空格

五:format()函数

        format()函数通过{}和:代替%。运用更加灵活。

print("{} {}".format("Hello", "World"))

print("{1} {0}".format("Hello", "World"))

print("{0} {1} {0}".format("Hello", "World"))

#>>>Hello World
#>>>World Hello
#>>>Hello World Hello

        也可以在字符串中添加变量

print("{name}'s score is {points}".format(name="Jujube", points="90"))

#>>>Jujube's score is 90
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值