47.python基础:字符串运算

1.字符串运算

  • demo01
a='hello'
b="hello"
c='''hello'''
d='''
hello
'''
print(id(a))
print(id(b))
print(id(c))
print(id(d))
print(a == b)
print(a is b)
print(a == c)
print(a is c)
print(a == d)
print(a is d)
2393970514032
2393970514032
2393970514032
2393970514288
True
True
True
True
False
False

== 比较的是内容
is 比较的是地址


  • demo02
#a, b均输入hello
a=input()
b=input()
print(a == b)
print(a is b)
print(id(a))
print(id(b))
hello
hello
True
False
1919556655472
1919556655536

input 函数会分配内存空间, 因此地址会改变


  • demo03
a='hello'
b='me'
print(a+b)
print(a,b)
print(a*2)
hellome
hello me
hellohello

a='hello'
print('he' in a)
print('he' not in a)
True
False

name='lucy'
print('%s说%s'%(name, 'hello'))
lucy说hello

print("haha \'")
print(r"haha \'")
haha '
haha \'

name='hello67world'
print('1-->',name[0:5])
print('2-->',name[2:5])
print('3-->',name[2:])
print('4-->',name[:5])
print('-----------')
print('1-->',name[5:-1])
print('2-->',name[:-2])
print('3-->',name[-1:])
print('4-->',name[-5:-1])
print('-----------')
print('1-->',name[11:-1])
print('2-->',name[:])
print('3-->',name[-1:-5:-1])
print('4-->',name[-1:-5:-2])
print('5-->',name[5:0:-1])
print('6-->',name[5:0:1])
print('7-->',name[::-1])
print('8-->',name[::-2])
1--> hello
2--> llo
3--> llo67world
4--> hello
-----------
1--> 67worl
2--> hello67wor
3--> d
4--> worl
-----------
1-->
2--> hello67world
3--> dlro
4--> dr
5--> 6olle
6-->
7--> dlrow76olleh
8--> drw6le

2.字符串内嵌函数

  • demo01
senence='hello world'
print('1-->',senence.capitalize())
print('2-->',senence.title())
print('3-->',senence.title().istitle())
print('4-->',senence.upper())
print('5-->',senence.lower())
1--> Hello world
2--> Hello World
3--> True
4--> HELLO WORLD
5--> hello world

  • demo02 : 验证码案例.
    random.randint():前闭后闭; randrange():前闭后开
import random
strs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
code=""
for i in range(4):
    code+=strs[random.randint(0, len(strs)-1)]
print("code:{}".format(code))
input_code = input("请输入验证码:")
if code.lower() == input_code.lower():
    print("欢迎登陆")
else:
    print("验证码输入错误")
code:Dcj6
请输入验证码:dcj6
欢迎登陆

  • demo03: 查找与替换
senence='index lucy lucky left hands'
print('R' in senence)
print(senence.find('R'))
print(senence.find('l'))
print(senence.find('l', senence.find('l')+1, len(senence)-1))
False
-1
6
11

  • demo04 :查找与替换
#find() rfind() lfind() index() rindex() lindex() replace() 
url='http://image.baidu.com/search/2F20150704212949_PSfNZ.jpeg'
filename=url[(url.rfind('/')+1):]
print(filename)
2F20150704212949_PSfNZ.jpeg

  • demo05 :中文转码
msg = "你好"
encode_msg = msg.encode("utf-8")
print(encode_msg)
decode_msg = encode_msg.decode("utf-8")
print(decode_msg)
b'\xe4\xbd\xa0\xe5\xa5\xbd'
你好

  • demo06 :文件格式
path = "C:\test\picture.jpg"
filename = path[path.rfind('\\')+1:]
if filename.startswith('p') and filename.endswith('jpg'):
    print('找到了')
else:
    print('没找到')
找到了

  • demo07 : msg.isalpha(), num.isdigit()
msg = "abd"
print(msg.isalpha())

sum = 0
for i in range(3):
    num = input("请输入数字:")
    if num.isdigit():
        sum += int(num)
print (sum)
True
请输入数字:1
请输入数字:2
请输入数字:3
6

  • demo08: '-'.join()
msg="hello"
new_msg = '-'.join(msg)
print(new_msg)

my_list = ['a', 'b', 'c']
result = ''.join(my_list)
print('result:', result)
print(type(result))
h-e-l-l-o
result: abc
<class 'str'>

  • demo09: lstrip(), strip()
msg='    hello  '
print(msg.lstrip()+'a')
print(msg.strip()+'a')
hello  a
helloa

  • demo10: split('-'), count('-')
msg = 'h-e-l-l-o'
print(msg.split('-', msg.count('-')))
print(msg.split('-', 2))
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l-l-o']

  • demo11: 输入两个字符串s1, s2; s1中删除s2中的字符
s1 = input('s1:')
s2 = input('s2:')
for i in s2:
    s1 = s1.replace(i, "")
print('s1:{}'.format(s1))
s1:hello world
s2:lo
s1:he wrd

  • demo12: 输入一个str, 如果有小写字母或者叠词, 就提示
s1 = input('s1:')
for i in range(len(s1)):
    if(s1[i] < 'A' or s1[i] > 'Z'):
        print('有小写字母')
        break
    elif (i < len(s1) -1 and s1[i] == s1[i+1]):
        print('有叠词')
D:\PythonStudying>python Demo03.py
s1:asd
有小写字母
D:\PythonStudying>python Demo03.py
s1:ASDD
有叠词
D:\PythonStudying>python Demo03.py
s1:ASDF

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,921评论 0 38
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,421评论 0 2
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,837评论 0 10
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,148评论 1 32
  • 今天中午爸爸带着我去小姨家玩。到了小姨家。我去小姨的屋里跟小姨玩。
    胡天然阅读 224评论 0 0