40923250 cp2020

  • Home
    • Site Map
    • reveal
    • blog
  • First
  • Hw1
    • PCH18
      • Laptop and Notebook Component Replacement
      • Troubleshooting Hard Drives
    • PCH19
      • Overview
      • AC Power
      • Proper Disposal Procedures
      • Security
  • HW2
    • 2-1 取得一甲分組數列
    • 2-2 是否有人加退選
    • 2-3 產生W3網頁html
  • Hw3
    • 14.移除重複項
    • 15.倒序
    • 16.密碼生成器
  • 學習日記
    • git clone
    • 刪除submodule
    • ORError
    • ssh keygen
  • python
    • Variables 變數
14.移除重複項 << Previous Next >> 16.密碼生成器

15.倒序

Reverse Word Order   

strings

Exercise 15 (and Solution)

Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string:

  My name is Michele

Then I would see the string:

  Michele is name My

shown back to me.

Discussion

Concepts for this week:

  • More string things

More string things

Python has a lot of interesting things you can do with strings. I will show a few here, but you can see many more methods that may or may not be useful at the official Python documentation about the string format.

Remember that strings are lists.

Splitting strings

You can “split” or tear apart strings based on a given set of characters. For example:

teststring = "this is a test"
  result = teststring.split("t")

And at the end, result will contain the list:

['', 'his is a ', 'es', '']

Instead of "t", you can write any character you want. If you do not include any character, it means “split on all whitespace”:

  teststring = "  this      has a lot    of   spaces and    tabs"
  result = testring.split()


Then result contains:

 ['this', 'has', 'a', 'lot', 'of', 'spaces', 'and', 'tabs']

Joining strings

You can also relatively easily “join” or “smush” strings together:

listofstrings = ['a', 'b', 'c']
  result = "**".join(listofstrings)

Then result will contain the string:

  a**b**c

Take a look at the official Python documentation for more information.

Ans.

#列出一字串
w = "there is a pig"
#拆了他
#字串.split("這裡填用以分割的字")可以以括弧中的字分割字串
print(w.split())

#方法1
w = "there is a pig"
A = w.split()
A.reverse()
print(A)

print("------")
#方法2
# Reversing a list	
#Syntax: A = w[start:stop:step]
#但我不知道為啥會整個倒過來...
w = "there is a pig"
A = w.split()
A = w[::-1]
print(A)

print("------")
#方法3
w = "there is a pig"
A = w.split()
for B in reversed(A):
    print(B)


14.移除重複項 << Previous Next >> 16.密碼生成器

Copyright © All rights reserved | This template is made with by Colorlib