Python学习01(输入输出、字符串)

本文详细介绍Python变量定义、条件语句、用户登录验证、字符串与整型操作、字符串API如find、format、split等,以及for循环使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Python定义变量和其他语言不同,前面不需要加上变量类型。示例如下: 

elem = input("please input something") # elem接收输入的字符串

2.条件语句中无else if,应写为elif

3.用户登录(三次机会重试)

count = 3
while count > 0:
    username = input(">>>")
    password = input(">>>")
    if username == "Tom" and password == "123": # 1.注意运算符和变量之间留有空格  2.不需要括号(逻辑关系复杂的时候需要添加)  3.Python中没有&&和||,只有and和or
        print("welcome login")
        break
    else:
        print("error")  
        count -= 1  # Python中没有一元运算符++和--

4.in的用法

if "hello" in "hello world":
    print("true")

5.类型 int 相关API

# 1.int()
str1 = "12345"            # 变量名命名为str时,会有一个警告
print(type(str1), str1)   # 1.这里的逗号前面不加空格,后面留有一个空格  2.type(str1)的结果是<class 'str'>
str2 = int(str1)          # 强制类型转换
print(type(str2), str2)

num = "15"
v = int(num, base=16)     # 结果为21,base = 16意味着15是16进制的数,21是15转换为十进制的值
print(v)

# 2.bit_length()
r = v.bit_length()        # 用二进制表示这个数,至少需要多少位
print(r)

6.字符串相关API

# 1 首字母大写
test = "alex"
v = test.capitalize()
print(v)

# 2 所有变小写,casefold更比lower更厉害,很多未知的对相应变小写
test = "ALeX"
v1 = test.casefold()
print(v1)
v2 = test.lower()
print(v2)

# 3 设置宽度,并将内容居中
# 20 代指总长度
# *  空白未知填充,一个字符(可以是中文,默认是空格),可有可无
test = "alex"
v = test.center(20, "中")
print(v)
test = "alex"
v = test.ljust(20, "*")  # 左边填充
print(v)

test = "alex"
v = test.rjust(20, "*")  # 右边填充
print(v)

test = "alex"
v = test.zfill(20)  # 用0填充
print(v)

# 4 去字符串中寻找,寻找子序列的出现次数
test = "aLexalexr"
v = test.count('ex')
print(v)
test = "aLexalexr"
v = test.count('ex', 5, 8)    # start:5     end:8
print(v)

# 5 以什么什么结尾 以什么什么开始
test = "alex"
v1 = test.endswith('ex')
v2 = test.startswith('ex')
print(v1, v2)
# 6 expandtabs,把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是8,这里设置为20
test = "username\temail\tpassword\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123"
v = test.expandtabs(20)
print(v)

# 7 从开始往后找,找到第一个之后,获取其位置,未找到则返回-1
test = "alexalex"
v = test.find('ex')
print(v)

# 8 index跟find方法类似,但是如果没有找到,那么程序不会返回-1,只会报错,所以find方法比index方法要好
test = "alexalex"
v = test.index('8')
print(v)

# 9 格式化,将一个字符串中的占位符替换为指定的值
test = 'i am {name}, age {a}'
print(test)
v = test.format(name='alex', a=19)  # 这里的符号和变量之间就不需要空格
print(v)
# 另一种方式
test = 'i am {0}, age {1}'
print(test)
v = test.format('alex', 19)
print(v)


# 10 格式化,以键值对的方式赋值
test = 'i am {name}, age {a}'
v1 = test.format(name='df', a=10)
v2 = test.format_map({"name": 'alex', "a": 19})
# 11 字符串中是否只包含 字母和数字
test = "123"
v = test.isalnum()
print(v)

# 12 是否是字母,汉字
test = "as2df"
v = test.isalpha()
print(v)

# 13 当前输入是否是数字
test = "二"                  # 1,②
v1 = test.isdecimal()        # 最常用
v2 = test.isdigit()
v3 = test.isnumeric()          
print(v1, v2, v3)    # False False True

# 14 判断字符串中所有字符是否都是可打印字符(in repr())或字符串为空。
# Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符(但不包括ASCII码中的空格(0x20))。可用于判断转义字符。
# ASCII码中第0~32号及第127号是控制字符;第33~126号是可打印字符,其中第48~57号为0~9十个阿拉伯数字;65~90号为26个大写英文字母,97~122号为26个小写英文字母。
test = "oiuas\tdfkj"
v = test.isprintable()
print(v)

# 15 判断是否全部是空格
test = "  "
v = test.isspace()
print(v)
# 16 判断是否是标题,标题是一句话所有字符首字母大写
test = "Return True if all cased characters in S are uppercase and there is"
v1 = test.istitle()
print(v1)
v2 = test.title()
print(v2)
v3 = v2.istitle()
print(v3)

# 17 将字符串中的每一个元素按照指定分隔符进行拼接
test = "你是风儿我是沙"
print(test)
v = "_".join(test)
print(v)

# 18 判断是否全部是大小写 和 转换为大小写
test = "Alex"
v1 = test.islower()
v2 = test.lower()
print(v1, v2)
v1 = test.isupper()
v2 = test.upper()
print(v1,v2)

# 19 移除指定字符串 指定字符串会以子串的形式匹配
test = "xa"
v = test.rstrip('9lexxexa')     # 能把"xa"移除
print(v)
# test.lstrip()
# test.rstrip()
# test.strip()
# 去除左右空白
v = test.lstrip()
v = test.rstrip()
v = test.strip()
print(v)
print(test)

# 20 对应关系替换
test = "aeiou"
test1 = "12345"

v = "asidufkasd;fiuadkf;adfkjalsdjf"
m = str.maketrans("aeiou", "12345")
new_v = v.translate(m)
print(new_v)    # 1s3d5fk1sd;f351dkf;1dfkj1lsdjf
# 21 分割为三部分
test = "testasdsddfg"
v = test.partition('s')
print(v)
v = test.rpartition('s')    # 从右边找第一个s分割
print(v)

# 22 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
test = "testasdsddfg"
v = test.split('s', 3)  # ['te', 'ta', 'd', 'ddfg']
print(v)

# 23 分割,只能根据,true,false:是否保留换行
test = "asdfadfasdf\nasdfasdf\nadfasdf"
# v = test.splitlines(True)   # ['asdfadfasdf\n', 'asdfasdf\n', 'adfasdf']
v = test.splitlines(False)  # ['asdfadfasdf', 'asdfasdf', 'adfasdf']
print(v)

# 24 大小写转换,大写变小写,小写变大写
test = "aLex"
v = test.swapcase()
print(v)

# 26 isidentifier() 方法用于判断字符串是否是有效的 Python 标识符
a = "def"
v = a.isidentifier()
print(v)

# 27 将指定字符串替换为指定字符串
test = "alexalexalex"
v = test.replace("ex", 'bbb')
print(v)
v = test.replace("ex", 'bbb', 2)    # 只替换两个ex
print(v)

其中最重要几个API

# join  split  find  strip  upper  lower  replace

7.for循环和字符串常用方法

# 一、for循环
# for 变量名 in 字符串:
#     变量名
# break    跳出当前循环
# continue     跳过剩余语句,进入下一轮循环
test = "hello"
index = 0
while index < len(test):    # while循环打印字符串里每一个字符
    v = test[index]
    print(v)
    index += 1
print('=======')

for elem in test:
    print(elem)

# 二、索引,下标,获取字符串中的某一个字符
v = test[3]
print(v)

# 三、切片
v = test[0:-1]
print(v)

# 四、获取长度
# Python3: len获取当前字符串中由几个字符组成
v = len(test)
print(v)

# 五、获取连续或不连续的数字,
# Python2中直接创建在内容中
# python3中只有for循环时,才一个一个创建
r1 = range(10)
r2 = range(1, 10)
r3 = range(1, 10, 2)
# 帮助创建连续的数字,通过设置步长来指定不连续
v = range(0, 100, 5)

for item in v:
    print(item)

8.字符串一旦创建,不可修改,一旦修改或者拼接,都会造成重新生成字符串

9.练习:根据用户输入的值,输出每一个字符以及当前字符所在的索引位置

# 获取字符串索引和对应字符
elem = "hello"
for index in range(len(elem)):
    print(elem[index], index)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值