Python字符串及练习题

1.变量名命名规则

# 中文是可以作为变量名的,但不建议
姓名 = "hello"
print(姓名)
# 变量名可以由字母,数字或者下划线;
# 变量名只能以字母或者下划线组成;
# 变量名不能是python的关键字: eg: if, elif, else,
#   eg: while, for, break,continue,pass
a_1hello = "hello"
print(a_1hello)
# hell@ = "hello"
# if = "hello"
# while = "hello"

# break = "hello"


2.字符串的定义方式

字符串常用的转义符号:
#   \n:换行
#   \t: 一个tab键
#   \': '
#   \": "
# 打印"hello"
# 打印guido's
# 打印"hello guido's python"
print('"hello"')
print("guido's")
print("\"hello guido\'s python\"")

print("%s\t%s" % ("hello", "world"))


s = "hello"
索引: 0,1,2,3,4, 索引值是从0开始的;
print(s[0])
print(s[4])
print(s[-1])        # 拿出字符串的最后一个子符;
切片
print(s[0:3])       # 切片时规则为s[start:end:step],从start开始,到end-1结束, 步长为step;
print(s[0:4:2])
print(s[:])             # 显示所有子符
print(s[:3])            # 显示前3个子符
print(s[::-1])          # 对于字符串倒序输出;
print(s[1:])            # 除了第一个子符之外, 其他全部显示;
# 重复
print(s*10)
连接
print("hello "+"world")
成员操作符 s = "hello", in, not in
print('he' in s)
print('aa' in s)

print('he' not in s)


字符串开头和结尾的匹配

# 找出字符串是否以xxxx结尾;
s = "hello.jpg"
print(s.endswith(('.png', '.jpg')))
url1 = "http://www.baidu.com"
url2 = "file:///mnt"
url3 = "https://www.baidu.com"
url4 = "ftp://www.baidu.com"
# 以什么开头;
print(url1.startswith(('https://', 'http://')))

print(url2.startswith("file://"))


字符串变量名判断

#[[:digit:]]
#[[:upper:]]
#[[:lower:]]
#[[:alnum:]]
#[[:space:]]
s = 'hello'
# 判断字符串里面的每个元素是否为什么类型, 一旦有一个元素不满

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值