字符串和字符串方法

字符串

  • 在 python 中,字符串的变量类型显示为 str。你可以使用双引号 " 或单引号 ’ 定义字符串
  • 定义字符串
my_string = 'this is a string!'
my_string2='this is also a string!'
#also,we can use backslash '/'to escape quotes
this_string='Simon\'s skateboard is in the garage'
print(this_string)
  • 字符串的常用操作
first_word ='hello'
second_word ='there'
print(first_word + second_word)#hellothere
print(first_word+' '+second_word)#hello there
print(first_word*5)#hellohellohellohellohello
print(len(first_word))#5
print(first_word[0])#h
print(first_word[1])#e
  • 字符串(相关练习)
ford_quote='whether you think you can,or you think you can\'t--you\'re right'
print(ford_quote)#whether you think you can,or you think you can't--you're right
  • 使用字符串连接和 len 函数计算某些电影明星的实际完整姓名的长度
given_name='william'
middle_names='bradley'
family_name='pitt'
name_length=len(given_name+' '+middle_name+' '+family_name)
#now we check to make sure that the name fits within the driving license character limit
driving_license_character_limit=28
print(name_length <= driving_license_character_limit)#ture
  • 我们刚刚使用函数 len 计算出字符串的长度。当我们向其提供整数 835 而不是字符串时,函数 len 会返回什么?
Error

字符串方法

  • python 中的方法和函数相似,但是它针对的是你已经创建的变量。方法特定于存储在特定变量中的数据类型。
  • 每个方法都接受字符串本身作为该方法的第一个参数。但是,它们还可以接收其他参数。我们来看看几个示例的输出。
my_string ='sebastian thrun'
my_string.islower()#ture
my_string.count('a')#2
my_string.find('a')#3
  • 可以看出,count 和 find 方法都接受另一个参数。但是,islower
    方法不接受参数。如果我们要在变量中存储浮点数、整数或其他类型的数据,可用的方法可能完全不同!
    字符串方法(相关练习)
  • 对浮点型对象调用 islower 等方法会发生什么?例如 13.37.islower()
  • 会出现错误, 方法 islower 属于字符串方法,而不是浮点数方法。不同类型的对象具有特定于该类型的方法。例如,浮点数具有
    is_integer 方法,而字符串没有。

练习字符串方法

my_name='my name is joh.'
cap =my_name.capitalize()
print(cap)#my name is joh.
ew =my_name.endswitch('li')
print(ew)#false
ind =my_name.index('is')
print(ind)#8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值