1.寫一個程序,在字串之間加上空格。
txt = "TodayIsFriday" first = True for letter in txt: if letter>='A' and letter<='Z': if first==True: first = False else: print(' ',end='') print(letter,end='')
Today Is Friday
2.寫一個程序,刪除字串之間的空格。
txt = " Today Is Friday" for letter in txt: if letter==' ': pass else: print(letter,end='')
TodayIsFriday
3.寫程式去除字串左邊的空格:
ltrim()-從字串左側刪除任何前導空格或指定字元。
txt = " Today Is Friday" alphabet = False for letter in txt: if letter==' ' and alphabet==False: pass else: alphabet = True print(letter,end='')
Today Is Friday
4.編寫程式去除字串右側的空格:
rtrim() - 刪除字串右側的任何前導空格或指定字元。
txt = "Today Is Friday " alphabet = False i = len(txt)-1 while i>=0: letter = txt[i] if letter==' ' and alphabet == False: pass else: alphabet = True end = i j = 0 while j<=end: print(txt[j],end='') j+=1 break i-=1
Today Is Friday
5.寫一個程式來刪除給定字串中不需要的空格:
txt = "Today Is Friday" i = 0 while i<len(txt): if txt[i] != ' ': print(txt[i],end='') else: if txt[i-1]!=' ': print(txt[i],end='') i+=1
Today Is Friday
遞迴:
函數呼叫自身。
什麼是函數?
設定帶有名稱的指令以實現特定任務。
循環迭代方法。
Recursion-遞迴方法。
範例:
def display(no): print(no, end=' ') no+=1 if no<=5: display(no) display(1)
1 2 3 4 5
使用遞歸編寫階乘程式:
def find_fact(no): if no==1: return 1 return no * find_fact(no-1) result = find_fact(4) print(result)
24
任務:
寫一個程式來刪除給定字串中不需要的空格:
strip()-刪除字串開頭和結尾的所有空白字元。
txt = " Today Is Friday " first=True for letter in txt: if letter==" ": pass else: if letter>='A' and letter<='Z': if first==True: first = False else: print(' ',end='') print(letter,end='')
Today Is Friday
使用遞歸以相反的順序編寫給定數字的程式:
def reverse_number(num,reverse=0): if num==0: return reverse return reverse_number(num//10,reverse*10+num%10) num=int(input("Enter the number:")) print(reverse_number(num))
Enter the number:123 321
寫一個程式來找出給定的數字是回文還是不使用遞歸:
def palindrome(num,count=0): if num==0: return count return palindrome(num//10,count*10+num%10) num=int(input("Enter the number:")) result=palindrome(num) if result==num: print("Palindrome") else: print("Not palindrome")
Enter the number:1221 Palindrome Enter the number:56878 Not palindrome
寫一個程序,使用遞迴找出斐波那契數:
def find_fibonacci(first_num,sec_num,no): if first_num > no: return print(first_num, end=" ") find_fibonacci(sec_num,first_num+sec_num,no) no = int(input("Enter the number: ")) find_fibonacci(0,1,no)
0 1 1 2 3 5 8
寫一個使用遞迴查找素數的程式:
def find_prime(no,div=2): if div<no: if no%div == 0: return False div+=1 return find_prime(no,div) else: return True no = int(input("Enter no. ")) print(find_prime(no))
Enter no. 12 False
以上是Day 字串函數和遞歸的詳細內容。更多資訊請關注PHP中文網其他相關文章!