第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當逗號(,)完成這項工作時,在Python中使用連接(+)有什么意義?

當逗號(,)完成這項工作時,在Python中使用連接(+)有什么意義?

一只斗牛犬 2023-10-18 22:04:34
print("This is a string" + 123)連接會引發(fā)錯誤,但使用逗號即可完成這項工作。
查看完整描述

6 回答

?
米脂

TA貢獻1836條經(jīng)驗 獲得超3個贊

正如您已經(jīng)被告知的,您的代碼會引發(fā)錯誤,因為您只能連接兩個字符串。在您的情況下,串聯(lián)的參數(shù)之一是整數(shù)。

print("This is a string" + str (123))

但你的問題更多的是“加號與逗號”。為什么人們應(yīng)該+工作時使用,

嗯,對于參數(shù)來說確實如此print,但實際上在其他情況下您可能需要連接。例如在作業(yè)中

A = "This is a string" + str (123)

在這種情況下,使用逗號會導(dǎo)致不同的(并且可能是意外的)結(jié)果。它將生成一個元組而不是串聯(lián)。


查看完整回答
反對 回復(fù) 2023-10-18
?
繁花如伊

TA貢獻2012條經(jīng)驗 獲得超12個贊

嘿,您正在嘗試連接字符串和整數(shù)。它會拋出類型錯誤。你可以嘗試類似的東西

print("This is a string"+str(123))

逗號 (,) 實際上并不是連接值,它只是以看起來像連接的方式打印它。另一方面,連接實際上會連接兩個字符串。


查看完整回答
反對 回復(fù) 2023-10-18
?
嚕嚕噠

TA貢獻1784條經(jīng)驗 獲得超7個贊

這是一個案例print()。但是,如果您確實需要字符串,則可以使用連接:

x = "This is a string, "+str(123)

得到你" This is a string, 123"

你應(yīng)該寫

x = "This is a string", 123

你會得到元組("This is a string",123)。那不是字符串,而是完全不同的類型。


查看完整回答
反對 回復(fù) 2023-10-18
?
12345678_0001

TA貢獻1802條經(jīng)驗 獲得超5個贊

如果變量中有 int 值,則可以使用 f-string(格式字符串)將其打印出來。格式需要更多輸入,例如print(("one text number {num1} and another text number {num2}").format(num1=variable1, num2=variable2)

x?=?123
print(("This?is?a?string?{x}").format(x=x))

上面的代碼輸出:

This?is?a?string?123


查看完整回答
反對 回復(fù) 2023-10-18
?
絕地?zé)o雙

TA貢獻1946條經(jīng)驗 獲得超4個贊

# You can concatenate strings and int variables with a comma, however a comma will silently insert a space between the values, whereas '+' will not. Also '+' when used with mixed types will give unexpected results or just error altogether.


>>> start = "Jaime Resendiz is"

>>> middle = 21

>>> end = "years old!


>>> print(start, middle, end)


>>> 'Jaime Resendiz is 21 years old!'


查看完整回答
反對 回復(fù) 2023-10-18
?
慕無忌1623718

TA貢獻1744條經(jīng)驗 獲得超4個贊

原因很簡單,它123是一種int類型,而你不能concatenate int使用str類型。


>>> s = 123

>>> type(s)

<class 'int'>

>>>

>>> w = "Hello"+ s

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: can only concatenate str (not "int") to str

>>>

>>>

>>> w = "Hello" + str(s)

>>>

>>> w

'Hello123'

>>>

您可以看到錯誤,因此您可以使用函數(shù)將s其值為字符串的變量轉(zhuǎn)換為字符串。但是在這種情況下,您想將字符串與其他類型連接起來嗎?我認為你應(yīng)該使用123str()f-strings


例子


>>> boolean = True

>>> fl = 1.2

>>> integer = 100

>>>

>>> sentence = f"Hello variables! {boolean} {fl} {integer}"

>>> sentence

'Hello variables! True 1.2 100'


查看完整回答
反對 回復(fù) 2023-10-18
  • 6 回答
  • 0 關(guān)注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號