Python 基础(二)

版权声明:如需转载请标注 https://blog.csdn.net/weixin_40973138/article/details/84038136

11. 截取字符串的某部分

使用切片[:]

>>> s = 'abcdefg'
>>> s[1:5]
'bcde'
>>> s[:5]
'abcde'
>>> s[5:]
'fg'
>>> s[-3:]
'efg'
>>> s[1:5:2]
'bd'

注意:

  • 字符始于0
  • 字符集不包含右边的端点,故字母f 不包含

切片功能异常强大,感兴趣者可另往查阅相关资料

12. 用一个字符串替换另一个字符串的某部分

使用replace 函数

>>> s = 'My name is Waao'
>>> s.replace('Waao','Jack')
'My name is Jack'

13. 将一个字符串转换为全部大写或全部小写

使用upperlower 函数

>>> 'Abc'.upper()
'ABC'
>>> 'Abc'.lower()
'abc'
>>> s = 'abc'
>>> s.upper()
'ABC'
>>> print(s)
abc

和大多数处理字符串的方式一样,upperlower 不会真正修改字符串,而是返回一个修改过的字符串副本

14. 有条件地运行命令

if语句

>>> x = 100
>>>if x < 200:
...	print('OK')
...elif x < 250:
...	print('NOT')
...else:
...	print('NONE')
...
OK

15. 比较值

小于 <
大于 >
小于等于 <=
大于等于 >=
等于 ==
不等于 != 或 <>

16. 逻辑运算符

and
or
not

17. 重复执行指令指定的次数

>>> for i in range(1,4):
...	print(i)
...
1
2
3

range(x,y) 会生成从xy 的列表,故运行次数为y-x

18. 重复执行指令,直到某些条件变化

使用while 语句,用法与C语言相似

>>> answer = ' '
>>> while answer != 'X':
...	answer = input('Enter command:')
...
Enter command:A
Enter command:B
Enter command:X

19. 中断循环

可使用break 退出whilefor 循环

>>> while True:
...	answer = input('Enter command:')
...	if answer == 'X':
...		break

20. 在Python 中定义函数并调用

函数的命名约定:与变量命名约定相同,名称应当以一个小写字母开头,若名称中包含多个单词,单词之间应当以下划线分隔

函数可指定默认值n=2

>>> def count_to_n(n=2):
...	for i in range(1,n):
...		print(i)
...
>>> count_to_n(3)
1
2
3
>>> count_to_n()
1
2

若函数需要返回值,则使用return

>>> def a_sentence(s):
...	return s + ' is me.'
...
>>> print(a_sentence(Waao))
Waao is me.

猜你喜欢

转载自blog.csdn.net/weixin_40973138/article/details/84038136