python(string)

前言

string(格式)

  • 例:
    a = ‘hello’
    b = ‘what’s up’
    c = “”"
    用戶管理系統
    1.添加用戶
    2.刪除用戶
    3.顯示用戶
    “”"
    print(b)
    print©
    print(type©)

顯示結果:

what's up

        用戶管理系統
        1.添加用戶
        2.刪除用戶
        3.顯示用戶

<type 'str'>

string(索引,切片,重複,連接,判斷)

  • index索引
    s = ‘hello’
    print(s[0])

      h
    

    print(s[1])

      e
    

    print(s[2])

      l
    
  • cut切片
    print(s[0:3]) #s[start:end-1]

      hel
    

    print(s[0:4:2])

      hl
    

    print(s[:])

      hello
    

    print(s[:3])

      hel
    

    print(s[1:])

      ello
    

    print(s[::-1])

      olleh
    
  • repeat重複
    print(s * 2)

      hellohello
    
  • link連接
    print(‘hello’ + ’ world’)

      hello world
    
  • judge判斷
    print(‘h’ in s)

      True
    

    print(‘f’ in s)

      False
    

string(練習:迴文)

示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。因此它不
是一個迴文數。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 爲 01 。因此它不是一個迴文數。

num = input('Num:')
if num == num[::-1]:
    print('ok')
else:
    print('failed')

string(判斷字符串屬性)

  • num
    print(‘123’.isdigit())

      True
    

    print(‘123abc’.isdigit())

      False
    
  • title
    print(‘Hello’.istitle())

      True
    

    print(‘HelLo’.istitle())

      False
    
  • words
    print(‘hello’.upper())

      HELLO
    

    print(‘HeLlO’.lower())

      hello	 
    

    print(‘hello’.islower())

      True
    

    print(‘HELLO’.isupper())

      True
    

    print(‘HELL1’.isalnum())

      True
    

    print(‘123’.isalpha())

      False
    

    print(‘qqq’.isalpha())

      True
    
  • filename(endswith,startswith)
    filename = ‘hello.loggg’
    if filename.endswith(’.log’):
    print(filename)
    else:
    print(‘error file’)

      error file
    

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

    if url3.startswith(‘http://’):
    print(‘ok’)
    else:
    print(‘failed’)

      ok
    

string(練習:判斷)

變量名是否合法:
1.變量名可以由字母,數字或者下劃線組成
2.變量名只能以字母或者下劃線開頭
s = ‘hello@’

1.判斷變量名的第一個元素是否爲字母或者下劃線 s[0]
2.如果第一個元素符合條件,判斷除了第一個元素之外的其他元素s[1:]

while True:
s = input('Str:')
if s[0].isalpha() or s[0] == '_':
    for i in s[1:]:
        if not i.isalnum or i == '_':
            print('illegal')
            break
    else:
        print('ok')
else:
    print('illegal!')

string(find,replace,count,split,join)

s = ‘hello world hello’

  • find
    print(s.find(‘hello’))

      0
    

    print(s.find(‘world’))

      6
    
  • rfind
    print(s.rfind(‘hello’))

      12
    
  • replace
    print(s.replace(‘hello’,‘westos’))

      westos world westos
    

    print(‘System Admin’.center(30))

               System Admin         
    

    print(‘System Admin’.center(30,’*’))

      *********System Admin*********
    

    print(‘System Admin’.ljust(30,’*’))

      System Admin******************
    

    print(‘System Admin’.rjust(30,’*’))

      ******************System Admin
    
  • count
    print(‘hello’.count(‘l’))

      2
    

    print(‘hello’.count(‘ll’))

      1
    

    print(len(‘hello’))

      5
    
  • split,join
    s = ‘172.25.254.250’
    s1 = s.split(’.’)
    print(s1)

      ['172', '25', '254', '250']
    

    print(s1[::-1])

      ['250', '254', '25', '172']
    

    date = ‘2019-04-15’
    date1 = date.split(’-’)
    print(date1)

      ['2019', '04', '15']
    

    print(’’.join(date1))

      20190415
    

    print(’/’.join(date1))

      2019/04/15
    

string(練習:出勤)

給定一個字符串來代表一個學生的出勤紀錄,這個紀錄僅包含以下三個字符>:
‘A’ : Absent,缺勤
‘L’ : Late,遲到
‘P’ : Present,到場
如果一個學生的出勤紀錄中不超過一個’A’(缺勤)並且不超過兩個連續的’L’(遲到),
那麼這個學生會被獎賞。
你需要根據這個學生的出勤紀錄判斷他是否會被獎賞。
示例 1:
輸入: “PPALLP”
輸出: True
示例 2:
輸入: “PPALLL”
輸出: False

s = input()
	 if s.count('A') <= 1 and s.count('LLL') == 0:
	     print(True)
	 else:
	     print(False)

或:

	 s = input()
	 print(s.count('A') <= 1 and s.count('LLL') == 0)

string(練習:句子逆序)

題目描述:
給定一個句子(只包含字母和空格), 將句子中的單詞位置反轉,單詞用空格分割, 單詞之間只有一個空格,前後沒有空格。
比如: (1) “hello xiao mi”-> “mi xiao hello”
輸入描述:
輸入數據有多組,每組佔一行,包含一個句子(句子長度小於1000個字符)
輸出描述:
對於每個測試示例,要求輸出句子中單詞反轉後形成的句子
示例1:
輸入
hello xiao mi
輸出
mi xiao hello

li = input().split()
print(li)
print(li[::-1])
print(' '.join(li[::-1]))

或:

print(' '.join(input().split()[::-1]))

string(練習:排除被包含字符)

題目描述:
輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。例如,>輸入”They are students.”和”aeiou”,則刪除之後的第一個字符串變成”Thy r stdnts.”
輸入描述:
每個測試輸入包含2個字符串
輸出描述:
輸出刪除後的字符串
示例1:
輸入
They are students.
aeiou
輸出
Thy r stdnts.

s1 = input('s1:')
s2 = input('s2:')
s3 = ''
for i in s1:
    for q in s2:
        if q == i:
            break
    else:
        s3 += i
print(s3)

string(練習:小學生習題)

設計一個程序,幫助小學生練習10以內的加法
詳情:
- 隨機生成加法題目;
- 學生查看題目並輸入答案;
- 判別學生答題是否正確?
- 退出時, 統計學生答題總數,正確數量及正確率(保留兩>位小數點);

import random

count = 0
right = 0

while True:
    a = random.randint(0,9)
    b = random.randint(0,9)
    print('%d+%d=' %(a,b))
    question = input('Please input your answer:(q for exit)')
    result = a + b
    if question == str(result):
        print('OK!')
        right += 1
        count += 1
    elif question == 'q':
        break
    else:
        print('Failed!')
        count += 1

percent = right / count
print('測試結束,共回答%d道題,正確個數爲%d,正確率爲%.2f%%' %(count,right,percent * 100))

後記

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