Python 程式形成一個新字串,該字串由給定字串中的前 2 個和後 2 個字元組成


當需要形成一個由給定字串中的前兩個和後兩個字元組成的新字串時,可以定義一個計數器,並可以使用索引來訪問特定範圍的元素。

以下是同一演示:

示例

 線上演示

my_string = "Hi there how are you"

my_counter = 0

for i in my_string:
   my_counter = my_counter + 1
new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ]

print("The string is ")
print(my_string)
print("The new string is ")
print(new_string)

輸出

The string is
Hi there how are you
The new string is
Hiou

說明

  • 定義一個字串並將其顯示在控制檯上。

  • 一個計數器初始化為 0。

  • 遍歷字串,並使用索引訪問前 2 個和後兩個元素。

  • 將其分配給變數。

  • 它是顯示在控制檯上的輸出。

更新於:2021-4-16

634 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告