Python自学(五)

本文是Python自学系列的第五篇,详细介绍了Python的基础语法,包括变量、数据类型、控制结构、函数以及模块的使用,帮助初学者掌握Python编程基础。
摘要由CSDN通过智能技术生成
※字符串
定义:
字符串(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值