python学习笔记---字符串

变量名的命名规则:
  • 中文是可以作为变量名的,但不建议
  • 变量名可以由字母,数字或者下划线;
  • 变量名只能以字母或者下划线组成;
  • 变量名不能是python的关键字: eg: if, elif, else,eg: while, for, break,continue,pass
字符串的特性:
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)

字符串特性的应用_回文数判断
##  题目要求:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样
的整数。

## 示例:

示例 1:
        输入: 121
        输出: true
示例 2:
        输入: -121
        输出: false
        解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
        输入: 10
        输出: false
        解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶:
你能不将整数转为字符串来解决这个问题吗?
# 方法1:
num = input('Num:')
print(num == num[::-1])



# 方法2: 无需将整形转化为字符串类型
num = int(input('Num:'))

# 如果为负数 或者为10,20,30....不是回文数;
if num < 0 or (num!=0 and num%10 == 0):
    print(False)
# 0是回文数;
elif num == 0:
    print(True)
else:
    back = 0
    while num > back:
        back = back * 10 + num % 10
        num //= 10     # num = num / 10
    print(num == back or num == back//10)

字符串开头和结尾匹配
#######找出字符串是否以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'
# 判断字符串里面的每个元素是否为什么类型, 一旦有一个元素不满足, 返回False;
print("123".isdigit())
print("123hfjhre".isdigit())
print("HELLO".isupper())
print("HELlO".isupper())

# title是标题, 判断某个字符串是否为标题, 第一个字母为大写,其他为小写;
print('Hello'.istitle())
print('HeLlo'.istitle())

# 检测变量是否为数字或数字字符串;
print("hello".isnumeric())
print("111".isnumeric())

字符串判断练习题_变量名的合法性
1. 判断变量名的第一个元素是否为字母或者下划线; s[0]
2. 如果第一个元素符合条件, 判断除了第一个元素的其他元素;s[1:]
# strip 去掉字符串左右两边的空格
var = input("变量名:").strip()
# 判断第一个字符是否合法;
if var[0] == "_" or var[0].isalpha():
    for char in var[1:]:  # 判断除了第一个字符之外的其他字符 # char: e,l,l,o
        if not (char.isalnum() or  char == "_"):
            print('变量名%s不合法' %(var))
            break
    else:
        print('变量名%s合法' %(var))
else:
    print("变量名不合法:第一个字符错误!")
字符串的搜索与替换
s = "hello world hello"

# find找到子串,并返回最小的索引值;
print(s.find("hello"))
print(s.find("world"))

# rfind找到子串,并返回最大的索引值;
print(s.rfind("hello"))

# 替换字符串中所有的“hello”为"westos"
print(s.replace("hello", "westos"))
字符串删除不需要的子符_应用于读取及清洗数据中
# strip: 删除字符串左边和右边的空格; 在这里空格是广义的: \n,\t,
s = " \t \n            hello    jhfkjhgkjrhgk  kjhkjrhgruhg"
print(s.strip())

# lstrip:删除字符串左边的空格;rstrip:删除字符串右边的空格
s = " \t \n            hello    jhfkjhgkjrhgk  kjhkjrhgruhg\n\t"
print(s.lstrip())
print (s.rstrip())
# 如何删除中间的空格?  # 通过replace间接实现
s = "hello world hello"
print(s.replace(" ", ""))

字符串对齐
print("学生管理系统".center(30))
print("学生管理系统".center(30, "*"))
print("学生管理系统".center(30, "#"))
print("学生管理系统".ljust(30, "*"))
print("学生管理系统".rjust(30, "*"))

print("hello %s" %('world'))
# 位置参数
print("{0} {1} {0} {2}".format(3,2,4))

j结果:

            学生管理系统            
************学生管理系统************
############学生管理系统############
学生管理系统************************
************************学生管理系统
hello world
3 2 3 4
字符串统计
print("hello".count('l'))       # 2
print("helloll".count('ll'))        # 2
字符串统计练习
给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符:

'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),
那么这个学生会被奖赏。

你需要根据这个学生的出勤纪录判断他是否会被奖赏。

示例 1:

输入: "PPALLP"
输出: True
示例 2:

输入: "PPALLL"
输出: False
s = input()
# if s.count('A')<=1 and s.count('LLL')==0:
#     print(True)
# else:
#     print(False)

print(s.count('A')<=1 and s.count('LLL')==0)

字符串的分离与连接
s = '172.25.254.789'
# ['172', '25', '254', '789']列表数据类型
# split对于字符串进行分离, 分割符为"."
s1 = s.split(".")
print(s1[::-1])

date = '2018-04-22'
date1 = date.split("-")
# 倒序显示, 即反转;
date2 = date1[::-1]
print("date1:%s" %(date1))
print("date2:%s" %(date2))

# 连接, 通过指定的连接符, 连接每个字符串;
print("".join(date2))
print("/".join(date2))
print("/".join("hello"))
字符串的内置方法
print(min('hHello'))
print(max('hello'))
# 返回索引以及字符
for i,j in enumerate("hello"):
    print(i,j)

s1 = "hello"
s2 = "worldhs"
# 将两字符串按照索引值一一对应
for i in zip(s1, s2):
    print(i)

print(len("hello"))   # 求字符串长度

结果:

H
o
0 h
1 e
2 l
3 l
4 o
('h', 'w')
('e', 'o')
('l', 'r')
('l', 'l')
('o', 'd')
5

猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81410836