2023-12-02|閱讀時間 ‧ 約 23 分鐘

Python 程式札記 : 字符串操作方法與輸入輸出

本文將介紹 Python 中的字符串操作方法與輸入輸出,從基本的索引、切片到進階的字符串方法,還有如何進行輸入輸出操作,這對於文本處理和用戶交互來說非常重要。

字符串操作

字符串支持多種操作,讓我們看看幾個基本操作:

索引

訪問特定位置的字符。

str1 = 'Hello, world!'
print(str1[1]) # 輸出 'e'

切片

獲取字符串的一部分。

str2 = "Python is fun."
print(str2[0:6]) # 輸出 'Python'

連接

將兩個字符串合併在一起。

str1 = 'Hello, world!'
str2 = "Python is fun."
print(str1 + " " + str2) # 輸出 'Hello, world! Python is fun.'

字符串方法

Python 的字符串提供了許多內建方法來進行處理,這裡有幾個常用的方法:

轉換大小寫

str1 = 'Hello, world!'
str2 = "Python is fun."
print(str1.lower()) # 輸出 'hello, world!'
print(str2.upper()) # 輸出 'PYTHON IS FUN'

分割字符串

str1 = 'Hello, world!'
print(str1.split(',')) # 輸出 ['Hello', ' world!']

尋找子字符串位置

使用 find()index() 查找子串位置。find() 在子串不存在時會返回 -1,而 index() 則會拋出異常。

str1 = 'Hello, world!'

position = str1.find('world')

print(position) # 輸出 7

移除開頭和結尾的空白

strip()方法用於移除字符串開頭和結尾的空白。

str3 = ' Hello, Python! '
print(str3.strip()) # 輸出 'Hello, Python!'

輸入輸出

輸出:print() 函數

print() 是 Python 中最常用的輸出函數,用於將信息顯示到屏幕上。

print('輸出字符串')
print(str1)

輸入:input() 函數

input() 函數用於從用戶那裡獲取輸入。

name = input('請輸入你的名字: ')
print('你好, ' + name)

😊 感謝你的耐心閱讀,若是你喜歡這篇內容,可以透過以下方式表達你的喜歡 😊

❤️按個愛心|💬留言互動|🔗分享此文|📌追蹤阿梧|☕請喝咖啡

分享至
成為作者繼續創作的動力吧!
歡迎來到 Hello Coding ! 程式札記,我會在這裡分享分享各種程式語言的學習心得,以及任何跟 Coding 相關的內容。這裡的內容會盡量簡單、實用,讓任何對程式設計有興趣的人都能從這裡得到收穫。
© 2024 vocus All rights reserved.