python学习之字符串操作

str = 'python'  # 定义一个字符串变量
print(id(str))

print(str)       # 打印整个字符串
print(str[0:-1]) # 打印字符串第一个到倒数第二个字符(不包含倒数第一个字符)
print(str[0])    # 打印字符串的第一个字符
print(str[2:5])  # 打印字符串第三到第五个字符(包含第五个字符)
print(str[2:])   # 打印字符串从第三个字符开始到末尾
print(str[0:])   #打印全部字符

new_str = str[:2]
print(new_str)
print(id(new_str))  #返回新的字符串
print(len(new_str)) #长度

#new_str[0]='m' #不能修改

str = "nothing is impossible"
str1 = "  nothing is impossible  "
str2 = "12nothing is impossible21"

print(str.index("is"))
print(str.replace("is", "was"))
print(str.split(" "))
print(str.strip())
print(str2.strip("12"))  # 传入的"12",其实就是"1"和"2"都会移除,是按照单个字符
print(str.count("o"))

print("abc" > "abd")
print("ab" > "a")
print("a" > "A")
print("key2" > "key1")

text='python'
print(tuple(text)) #转元组
print(list(text))  #转列表

l = ['h','e','l','l','o']   #列表转字符串
print(''.join(l))
print('.'.join(l))

t = ('1','2','3','4','5')    #元组转字符串
print(''.join(t))

  str函数测试:

l = ['h','e','l','l','o']
print(str(l))

t = ('1','2','3','4','5')
print(str(t))

结果:输出字符串形式的列表和元组
['h', 'e', 'l', 'l', 'o']
('1', '2', '3', '4', '5')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值