Python interview one hundred questions - the core foundation (2)

table of Contents

  1. How to detect whether or not a character string can be transformed into
  2. How to reverse a string
  3. Integer and floating point format
  4. As well as an escape character string format
    usage 10.print function

06. How to detect whether or not a character string can be transformed into

Here Insert Picture Description

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

to sum up
Here Insert Picture Description

07. How to reverse a string

Here Insert Picture Description

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

s2 = s1[::-1]

to sum up
Here Insert Picture Description

08. integer and floating point format

Here Insert Picture Description

#格式化整数
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

to sum up
Here Insert Picture Description

09. character and string escape format

Here Insert Picture Description

#同时输出单引号和双引号
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
			 ''')	#三个双引号也可以

to sum up
Here Insert Picture Description

10.print usage function

default print function, separated by spaces, and newline

#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

to sum up
Here Insert Picture Description

Published 11 original articles · won praise 3 · Views 927

Guess you like

Origin blog.csdn.net/qq_36551226/article/details/104173645