Python之字符串

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 ' + 'python')
# 成員操作符
print('he' in s)
print('aa' in s)
print('he' not in s)

去除左右兩邊的空格

"""
注意:去除左右兩邊的空格,空格爲廣義的空格 包括:\n \t
>>> s = '      hello     '
>>> s
'      hello     '
>>> s.lstrip()
'hello     '
>>> s.rstrip()
'      hello'
>>> s = '\n\thello     '
>>> s
'\n\thello     '
>>> s.strip()
'hello'
>>> s = 'helloh'
>>> s.strip('h')
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')
'lloh'
>>>
"""

判斷數字

"""
[[:digit:]]
"""
# 只要其中有一個元素不滿足,就返回False
print('1234dfwew'.isdigit())
print('21312reqfeq'.isalpha())
print('vdsvdsv31213@#!#!@##!'.isalnum())

變臉名是否合法

1.變量名可以由字母,數字或者下劃線組成
 2.變量名只能以字母或者下劃線開頭

while True:
    s = input('變量名:')
    if s == 'exit':
        print('退出')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not(i.isalnum() or i == '_'):
                print('%s變量名不合法' %(s))
                break
        else:
            print('%s變量名合法' %(s))
    else:
        print('%s變量名不合法' %(s))

字符串的對齊

print('學生管理系統'.center(30))
print('學生管理系統'.center(30,'*'))
print('學生管理系統'.center(30,'@'))
print('學生管理系統'.ljust(30,'*'))
print('學生管理系統'.rjust(30,'*'))

# 替換字符串中的'hello' 爲'westos'
print(s.replace('hello','westos'))

print(len('westos'))

字符串的分離和連接

s = '172.52.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

# 連接,通過指定的連接符,連接每個字符串
print(''.join(date1))
print('/'.join(date1))
print('@'.join('hello'))

字符串匹配開頭和結尾

# filename = 'hello.log'
# if filename.endswith('.log'):
#     print(filename)
# else:
#     print('error')

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('爬取該網頁')
else:
    print('錯誤網頁')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章