Day6-总结

2019-06-11  本文已影响0人  SheeranED

一.认识字符串

1.什么是字符串(str)

print('hello' == 'heoll')  # 字符串有序,False

2.字符串中的内容

str5 = '\u4eff'
print(str5)    
num = 0                             
for code in range(0x4e00, 0x9fa5+1):
    num += 1                        
    if num % 30 == 0:               
        print()                     
    print(chr(code), end=' ')       
str6 = r'\tabc\n123\u4e03'   
print(str6)                  

二.字符串操作

1.获取字符

1.1获取单个字符
1.2获取部分字符(字符串切片)
str2 = 'hello+python'
print(str2[-1:4:-1]) # nohtyp+
1.3获取部分字符

2.遍历字符串

2.1直接遍历拿到每个字符
for item in 'hello world':
    print(item)
for item in 'hello world'[::-1]:
    print(item)
2.2通过遍历下标遍历字符串
str3 = 'hello'
for index in range(len(str3)):
    print(index, str3[index])
for index in range(-1, -len(str3)-1, -1):
    print(index, str3[index])

三.字符串相关运算

1.数学运算:+ *

print('abc'*3)

2.比较运算

print('ac' > 'aa') # True
str4 = '你好吗? Hello ^_^; Oh~ 天哪!'
count1 = 0
for item in str4:
    if 'a' <= item <= 'z':
        count1 += 1
print(count1)

count2 = 0
for item in str4:
    if '\u4e00' <= item <= '\u9fa5':
        count2 += 1
print(count2)

count3 = 0
for item in str4:
    if 'a' <= item <= 'z' or 'A' <= item <= 'Z':
        count3 += 1
print(count3)

3.in / not in

print('abc' in 'a2b3c') # False

4.len()

5.str(数据) - 将指定的数据转化成字符串

6.格式字符串:在字符串中用格式占位符来表示字符串中变化的部分

name = input('姓名')
age = int(input('年龄'))
message = '我是%s,今年%d岁' % (name, age)
print(message)

7.字符串相关的方法

str1 = 'abc'
print(str1.center(7, '*'))
str2 = 'wwwwwwwfffffff'
print(str2.count('w'))
print('*'.join('abc')) # a*b*c
str3 = '    sfa     '
str3 = str3.lstrip()
str3 = str3.rstrip()
str3 = str3.strip()
print(str3)
上一篇 下一篇

猜你喜欢

热点阅读