Python str() 函式



Python 的str()函式用於將給定值轉換為字串。字串是用於表示文字的字元序列。字元可以是任何單個字母、數字、符號或空格。

在 Python 中,您可以透過將字元序列用單引號 (' ') 或雙引號 (" ") 括起來來建立字串。

語法

以下是 Python str() 函式的語法:

str(x)

引數

此函式將您要轉換為字串的值 'x' 作為引數。

返回值

此函式返回一個字串物件。

示例 1

在下面的示例中,我們使用 str() 函式將整數“42”轉換為字串:

num = 42
str_num = str(num)
print('The string value obtained is:',str_num)

輸出

以上程式碼的輸出如下:

The string value obtained is: 42

示例 2

在這裡,我們使用 str() 函式將浮點數“3.14”轉換為字串:

float_num = 3.14
str_float = str(float_num)
print('The string value obtained is:',str_float)

輸出

以上程式碼的輸出如下:

The string value obtained is: 3.14

示例 3

在這裡,我們使用 str() 函式將布林值“True”轉換為其字串表示:

boolean_value = True
str_boolean = str(boolean_value)
print('The string value obtained is:',str_boolean)

輸出

獲得的結果如下所示:

The string value obtained is: True

示例 4

在本例中,str() 函式將列表“[1, 2, 3]”轉換為字串表示:

my_list = [1, 2, 3]
str_list = str(my_list)
print('The string value obtained is:',str_list)

輸出

以上程式碼的輸出如下:

The string value obtained is: [1, 2, 3]

示例 5

最後,我們使用 str() 函式將複數“(2+3j)”轉換為其字串表示:

complex_num = complex(2, 3)
str_complex = str(complex_num)
print('The string value obtained is:',str_complex)

輸出

產生的結果如下:

The string value obtained is: (2+3j)
python_type_casting.htm
廣告