Python面試一百題——核心基礎(2)

目錄

  1. 如何檢測一個字符串是否可以轉換爲數字
  2. 如何反轉字符串
  3. 格式化整數和浮點數
  4. 字符串轉義字符以及格式
    10.print函數的用法

06.如何檢測一個字符串是否可以轉換爲數字

在這裏插入圖片描述

s1 = '12345'
print(s1.isdigit())
s2 = '12345e'
print(s2.isalnum())

總結
在這裏插入圖片描述

07.如何反轉字符串

在這裏插入圖片描述

s1 = 'abcde'
s2 = ''
for c in s1:
	s2 = c + s2
print(s2)
edcba

s2 = s1[::-1]

總結
在這裏插入圖片描述

08.格式化整數和浮點數

在這裏插入圖片描述

#格式化整數
n = 1234
print(format(n, '10d'))
      1234
print(format(n, '0>10d'))
0000001234
print(format(n, '0<10d'))
1234000000

#格式化浮點數
x1 = 123.456
x2 = 30.1
print(format(x1, '0.2f'))	#保留小數點後兩位
123.46
print(format(x2, '0.2f'))
30.10

#描述format函數
print(format(x2, '*>15.4f'))	#右對齊,********30.1000
print(format(x2, '*<15.4f'))	#左對齊,30.1000********
print(format(x2, '*^15.4f'))	#中間對齊,****30.1000****
print(format(123456789, ','))	#用千位號分隔,123,456,789
print(format(1234567.1235648, ',.2f'))	# 1,234,567.12
#科學計數法輸出(e大小寫都可以)
print(format(x1, 'e'))	# 1.234560e+02
print(format(x1, '0.2e'))	# 1.23e+02

總結
在這裏插入圖片描述

09.字符串轉義字符以及格式

在這裏插入圖片描述

#同時輸出單引號和雙引號
print('hello "world"')	# hello "world"
print("hello 'world'")	# hello 'world'
print('"hello" \'world\'')	# "hello" 'world'

#讓轉義符失效(3種方法:r、repr和\)
print(r'Let \'s go!')	# Let \'s go!
print(repr('hello\nworld'))	# 'hello\nworld'
print('hello\\nworld')	# hello\nworld

#保持原始格式輸出字符串
print('''
		hello
			 world
			 ''')	#三個雙引號也可以

總結
在這裏插入圖片描述

10.print函數的用法

print函數默認空格分隔,並且換行

#print函數默認空格分隔,並且換行
#用逗號分隔輸出的字符串
print('aa', 'bb', sep=',')	# aa,bb
print('aa', 'bb', sep='中國')	# aa中國bb

#不換行
print('hello', end=' ')
print('world')	# hello world

#格式化
s = 's'
print('This is %d word %s' % (10, s))
# 佔位符有點過時了,推薦使用format

總結
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章