一、Python字符串概述
Python字符串是程序中常用的數據類型,可以存儲文本、數字、符號等信息。Python中,字符串使用一對單引號、雙引號或三引號表示,其中三引號可以表示多行字符串。例如:
string1 = 'Hello world!' string2 = "Python is wonderful." string3 = ''' This is a multiline string. '''
字符串可以進行拼接、替換、分割等操作,以下將對這些操作進行詳細闡述。
二、字符串拼接和替換
Python中,字符串可以通過“+”運算符拼接,或使用.format()方法替換指定位置的字符串。
string1 = 'Hello'
string2 = 'world!'
string3 = string1 + ' ' + string2
print(string3) # 輸出:Hello world!
name = 'Tom'
age = '18'
info = 'My name is {}, and I am {} years old.'.format(name, age)
print(info) # 輸出:My name is Tom, and I am 18 years old.
三、字符串分割和連接
字符串可以通過.split()方法進行分割,或使用.join()方法進行連接。
string = 'apple,banana,orange'
fruits = string.split(',')
print(fruits) # 輸出:['apple', 'banana', 'orange']
delimeter = '; '
string = delimeter.join(fruits)
print(string) # 輸出:'apple; banana; orange'
四、字符串格式化
字符串格式化是Python中常用的功能,可以將變量的值按照指定的格式輸出。常用的格式化符號包括:%d(整數)、%f(浮點數)、%s(字符串)等。例如:
age = 18
print('I am %d years old.' % age) # 輸出:I am 18 years old.
pi = 3.1415926
print('The value of pi is %.2f.' % pi) # 輸出:The value of pi is 3.14.
name = 'Tom'
print('My name is %s.' % name) # 輸出:My name is Tom.
另外,Python中也支持使用.format()方法進行字符串格式化,例如:
age = 18
print('I am {} years old.'.format(age)) # 輸出:I am 18 years old.
pi = 3.1415926
print('The value of pi is {:.2f}.'.format(pi)) # 輸出:The value of pi is 3.14.
name = 'Tom'
print('My name is {0} and I am {1} years old.'.format(name, age)) # 輸出:My name is Tom and I am 18 years old.
五、表達式求值
Python中,字符串還可以表示數學表達式,可以使用eval()函數進行求值。eval()函數可以將一個字符串作為Python代碼進行求值,並返回結果。例如:
result = eval('1 + 2 + 3')
print(result) # 輸出:6
x = 2
y = 3
expression = '{} * {} + 1'.format(x, y)
result = eval(expression)
print(result) # 輸出:7
六、總結
Python字符串是程序中常用的數據類型,可以存儲文本、數字、符號等信息。通過字符串拼接、替換、分割和連接,可以將字符串的內容進行修改和組合。字符串格式化可以讓程序輸出更加清晰、易於理解的信息。表達式求值在一些場景下也非常有用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/183004.html
微信掃一掃
支付寶掃一掃