sum()转字符串_Python字符串与内置函数
字符串
創建變量來保存字符串 字符串可以通過單、雙、三引號創建字符串
message?=?"Hello,world"#變量mseeage,值為'hello,world'print(message)
輸出結果:Hello,world
Python3,有3種數值類型分別為:int(整形)
#創建變量為a,值為496a?=?496?
#type查看類型
print(type(a))
輸出結果:
float(浮點型) 十進制的存儲方式 輸入的數字中有小數點
e?=?2.718281828print(type(e))
輸出結果:
complex(復數) 復數分為實數和虛數兩部分 創建復數,先輸入實數部分 然后是虛數部分,結尾寫j 實數和虛數部分可以分開顯示 .real屬性可以輸出實數值 .imag屬性可以輸出虛數值
z?=?2?-?6.1jprint(type(z))
z.real
z.imag
輸出結果:
運算中有4種運算符:+ - * / 先要了解數值間的轉換局限 任何整數可以當作浮點數 在int最后加.0就能變為float或通過float()方法轉,但返過來不一定行
x?=?28?#inty?=?28.0?#float
float(28)
3.14是小數非整數
int(3.14)???#如果將其轉為int,會先四舍五入,然后轉為int,不再是同一個數字了,可以說int比范圍更小,反之float比int范圍大
x?=?1.732?#float
1.732?+?0j???#浮點數可以轉為復數,在float未尾加+0j就能變為complex
complex(1.732)#或通過complex()方法轉
float(1.732+0j)?#如果將complex轉為float,會報錯,所以說float比complex范圍更小,反之complex比float范圍更大
a?=?2?#int
b?=?6.0?#float
c?=?12?+?0j?#complex
py會自動將范圍小的轉為范圍大的類型
a?+?b?#int+float,float比int范圍大,py將int轉為float,再加結果是8.0是float非int
b?-?a?#float-int,int比float范圍小,py將a變為float,再減,結果4.0是float
a?*?7?#int*int,結果14也是int
c?/?b?#complex/float,float比complex范圍小,b轉為complex,再除,結果2+0j,值大小和2一樣,但存儲為復數類型,因為有虛數部分存在,py用j而不是不表示-1開根
16/5?#兩個整數相除,結果是浮點型
20/5#即使沒有余數,結果也是浮點型
16%5#%取余運算會返回余數
16//5#//可以返回商
別忘了運算中的規定,除數不得為0,不然py中會報錯ZeroDivisionError,除法要小心,除非確定分母不是零,必須要為這種可能做準備
內置函數文件 第一個要知道的函數是dir(),目錄directory的縮寫 顯示當前模塊的屬性列表 輸出結果:['annotations', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec']
當第一次啟動解釋器,會有4個標準對象, 現在學習__builtins__,這是一個包含公共對象的模塊,想看__builtins__對象中的內容,查看__builtins__對象的目錄,使用dir(builtins)即可
lst?=?dir(__builtins__)print(lst)
輸出結果:['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', 'build_class', 'debug', 'doc', 'import', 'loader', 'name', 'package', 'spec', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 該表中包含了很多可用的函數和類型,想看具體一項目的使用方法,在函數help()中指定其名 例如查看一下函數pow()用法
lst?=?help(pow)print(lst)
輸出結果:pow(base, exp, mod=None) #有三個參數 Equivalent to baseexp with 2 arguments or baseexp % mod with 3 arguments
Some types, such as ints, are able to use a more efficient algorithm wheninvoked using the three argument form.
lst?=?pow(2,10)
print(lst)
輸出結果:1024
學習hex函數,依舊使用help()
lst?=?help(hex)print(lst)
輸出結果:Help on built-in function hex in module builtins:
hex(number, /) Return the hexadecimal representation of an integer.
>>>?hex(12648430)'0xc0ffee'
不需要導入庫,直接用即可,hex的輸入參數是數字類型
i?=?hex(10)print(i)
輸出結果:0xa
注意,結果在幫忙文檔中說是字符串,因為有引號,也表明是字符串,還要知道在Py中十六進制以0x開頭,如果想把十六進制轉回十進制,直接輸入十六進制值,注意就不要寫引號了,Py解釋器才會把它當作數字而不是字符串
布爾類型 布爾類型是Py內置的數據類型,只有True和False兩個值,注意它們都要大寫,輸入True,Py返回True,如果輸入不當,報錯NameError.False同理,大寫才正常,反之報錯。
比較兩個對象時會用到布爾類型 變量a和b,值分別為3和5
a?=?3b?=?5
通過==進行是否相等比較
a?==?b??#結果顯示False,a和b是不同的整數,注意使用=是賦值操作,==是相等比較.
a?!=?b??#除此之外,測試相等還可以使用。!=不相等符號測試,因為a,b不相等,所以返回True
此外,編程語文中通常表示邏輯非,等價于不等于,最后測試兩個數字是否相等,還可以通過大小判斷
a?>?b?#a是否大于b,False
a?#a是否大小b,True
type(True)?#通過type()看它們類型
type(False)?顯示都是Bool,還可以通過傳值給bool構造器來創建布爾
例如,傳數值給它
bool(28)#輸出True
bool(-2.71825)
bool(0)?#輸出False,在py中0認為是False,其他數字都是True
還可以將字符串轉為布爾
bool('Turing')?輸出True
bool('')?輸出False,Py中空的字符串認為是False,其他字符串都是True,特殊值為False,其他為True
可以將其他類型轉為布爾類型,也可以將布爾轉為其他類型
str(True)?#返回'True',True因為有引號,所以是字符串類型,布爾類型沒有引號
str(False)?#同理
還可以將布爾轉為數字
int(True)?#返回1
int(False)?#返回0
5?+?True?#數字和True相加會發生什么,Py會認為將True和整數相加,都先轉為整數,然后求和
10?*?False?#返回0,就像之前講的運算操作一樣,把False當作0,然后相乘,也許不是你要的結果
重點:Py中True當作1,False當作0
datetime模塊
#首先導入datetime模塊import?datetime
#鍵入dir(datetime)查看其內部列表
import?datetime
time?=?dir(datetime)
print(time)
#輸出結果:
['MAXYEAR',?'MINYEAR',?'__builtins__',?'__cached__',?'__doc__',?'__file__',?'__loader__',?'__name__',?'__package__',?'__spec__',?'date',?'datetime',?'datetime_CAPI',?'sys',?'time',?'timedelta',?'timezone',?'tzinfo']
#模塊中包含date、time、datetime三個類
#date類表示日期????
#time類表示時間???
#datetime類是date現time類的結合體,它是一個功能齊全的類,提供所需的一切來指定一個精確的時間點
先學習date類,在使用新類前,養成看幫助文檔的好習慣
time?=?help(datetime.date)
print(time)
#輸出結果
?----------------------------------------------------------------------
?class?date(builtins.object)
?|??date(year,?month,?day)?-->?date?object
#顯示如何創建date對象,指定year,month,day才能創建一個date
?|??----------------------------------------------------------------------
?|??Data?and?other?attributes?defined?here:
?|??
?|??max?=?datetime.date(9999,?12,?31)
?|??
?|??min?=?datetime.date(1,?1,?1)
?|??
?|??resolution?=?datetime.timedelta(days=1)
????
文檔中顯示支持從1年到9999年,編寫任何代碼都會持續一段時間
gvr?=?datetime.date(1956.1.31)?#創建變量gvr,這是Python創始人的生日
print(gvr)
#輸出結果:
1956-01-31
#可以單獨訪問year,month,day的值
print(gvr.year)
print(gvr.month)
print(gvr.day)
#datetime模塊中還有timedelta類,用來修改日期
mill?=?datetime.date(2000,1,1)?#創建變量maill
dt?=?datetime.timedelta(100)?#創建變量dt,正數代表加,反之為減
print(mill+dt)?#輸出結果:2000-04-10
注意:Py默認時間格式:年-月-日?? yyyy-mm-dd,但也可按個人喜好的格式設置
了解下格式字符串代碼
顯示一天的全寫,然后是月,最后是年
有兩種方式輸出這種格式
傳統方式對日期使用strftime方法,然后在其中指定格式代碼
print(gvr.strftime("%A,%B,%d,%Y"))#星期的全寫(星期三為Wednesday),月份的全寫(4月份為April),常用日期,4個數字表示的年份
message?=?"GVR?was?born?on?{:%A,%B,%d,%Y}."?#創建一個格式字符串,可以先輸入任何你喜歡的文本到日期格式部分,寫{:%A,%B,%d,%Y},現在輸出message.
print(message.format(gvr))??#調用.format()方法,值是日期或時間對象
dir(datetime)???#三個核心方法,date,time,datetime,使用這三個類創建對象
用date類創建日期
launch_date?=?datetime.date(2017,3,30)
launch_time?=datetime.time(22,27,0)??#用time類創建時間
launch_datetime?=?datetime.datetime(2017,3,30,22,27,0)??#最后用datetime類創建日期時間都有的變量,前三個參數,年,月,日,后三個參數時,分,秒,輸出三個對象,看有什么不同
print(launch_date)
2017-03-30???????#launch_date只有日期信息
print(launch_time)
22:27:00??????????#launch_time只有時間信息
print(launch_datetime)
2017-03-30?22:27:0????#launch_datetime日期時間都有
像date對象一樣,time也可輸出每部分值
print(launch_time.hour)
print(launch_time.minute)
print(launch_time.second)
launch_datetime也可單獨輸出
print(launch_datetime.year)
print(launch_datetime.month)
print(launch_datetime.day)
print(launch_datetime.hour)
print(launch_datetime.minute)
print(launch_datetime.second)
另一個常見問題,訪問當前日期和時間
使用datetime類中的today()方法
顯示當前日期和UTC格式時間
now?=?datetime.datetime.today()#顯示代碼運行時的日期時間
print(now)
輸出結果:
2020-11-16?20:01:44.131491
是否有提到datetime類可以記錄到毫秒級
print(now.mictosecond)?#像輸出其他部分一樣,使用.microsecond,這是相當精確的
另一個常見操作是,將獲取datetime字符串轉為datetime對象,來實操一下,創建字符串
moon_landing?=?"7/20/1969"
使用datetime類中的strptime方法,將時間字符串解析為datetime,方法名字有點詭異,尤其用于解析時期時間,建議改為parseString
moon_landing_datetime?=?datetime.datetime.strptime(moon_landing,"%m/%d/%Y")#第一個參數是字符串,第二個參數是格式,和之前datetime格式一樣,打印就會看到標準的Py日期格式
print(moon_landing_datetime)?#此時輸出就是對象而非字符串
1969-07-20?00:00:00
print(type(moon_landing_datetime))
<class?'datetime.datetime'>?#輸出就是datetime類中的實例類型
總結
以上是生活随笔為你收集整理的sum()转字符串_Python字符串与内置函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 吕布机器人唤醒方式能换么_《王者荣耀》推
- 下一篇: 【论文党福利】如何提取图像中的数据