※字符串
定义:
字符串(string)是一个字符的序列
使用成对的单引号或双引号括起来,或者使用三引号(保留字符串中全部信息)
基本运算:
1、长度(len())
>>> s = "hello world"
>>> len(s)
11
2、拼接(+)
>>> s + "abcd"
'hello worldabcd'
3、重复(*)
>>> s * 3
'hello worldhello worldhello world'
4、成员运算符(in):判断一个字符串是否是另一个字符串的子串,返回值:T或F
>>> "hi" in s
False
>>> "my name is vivien" in s
False
>>> "world" in s
True
5、枚举(for):枚举字符串的每个字符
>>> my_str = "hello world"
>>> for char in my_str:
print(char)
h
e
l
l
o
w
o
r
l
D
实例:编写vowels_count函数,计算一个字符串中元音字母(aeiou或AEIOU)的数目
def vowels_count(s):
count = 0
for c in s:
if c in "aeiouAEIOU":
count += 1
return count
str = input("please input a string :")
print("元音字母个数为:",vowels_count(str))
运行结果:
please input a string :hello
元音字母个数为: 2
◎字符串索引(index):
字符串中每一个字符都有一个索引值(下标)
索引从0(前向)或-1(后向)开始
索引运算符[ ]
>>> s = "hello world"
>>> s
'hello world'
>>> s[2]
'l'
>>> s[5]
' '
>>> s[6]
'w'
>>> s[-2]
'l
Python自学(五)
最新推荐文章于 2021-09-17 23:14:04 发布