Python数字、字符串

2021-06-29 23:05

阅读:424

标签:highlight   cas   ndt   pre   end   ignore   说明   格式化   二进制   

1. 数字

byte

  在python3中最重要的特性是对文本和二进制数据做了更加清晰的区分,python3不会以任意隐式方式混用字节型和字符型,也因此在python3中不能拼接字符串和字节包(python2中可以,会自动进行转换),也不能在字节包中搜索字符串,也不能将字符串传入参数为字节包的函数。

  需要注意的是,在网络数据传输过程中,python2可以通过字符串(string)方式传输,但是python3只能通过二进制(bytes)方式来传输,因此要对传输文本进行转换。

String与bytes转换: 

技术分享图片

sng = "人生苦短"

b_sng = sng.encode(encoding=‘utf-8‘)
print("byte:",b_sng)

s_sng = b_sng.decode(encoding="utf-8")
print("str:",s_sng)

#string类型---->byte类型  --encode
#byte类型 ----->string类型 --decode
#encode()和decode()方法中默认了编码为utf-8,建议将编码加上。

‘‘‘
结果:
byte: b‘\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad‘
str: 人生苦短
‘‘‘

 

整型

i = 1
print(type(i))



‘‘‘

‘‘‘

浮点型

f = 3.0
print(type(f))



‘‘‘

‘‘‘

复数类型

c = 3+4j
print(type(c))



‘‘‘

‘‘‘

布尔型

b = True
print(type(b))
b = False
print(type(b))

if 1 :
    print("1为True")
if 0 :
    print("0为Flase")
    

‘‘‘

1为True
‘‘‘

   使用python不需要声明变量类型,由python内置的基本数据类型来管理变量,在程序后台实现数值与类型的关联,以及类型的转换等操作。

 

2. String

  python有三种字符串表示方式:单引号、双引号、三引号。单引号和双引号作用一样。三引号可以输入单引号、双引号或换行等字符。三引号的另一个用法是制作文档字符串。python的每个对象都有一个属性__doc__,这个属性用于描述该对象的作用。

#单引号
s = ‘hello‘
#双引号
s = "hello"
#单引号双引号
s = "I‘m a student!"
print(s)
#三引号
s = ‘‘‘he say:"hello!"
    ‘‘‘
print(s)

#三引号说明注释
class Hello:
    ‘‘‘ hello class ‘‘‘
    def printHello():
        ‘‘‘ print hello ‘‘‘
        print("Hello world")
print("__doc__:",Hello.__doc__)
Hello.printHello()

 

  1 def capitalize(self): # real signature unknown; restored from __doc__
  2         """
  3         S.capitalize() -> str
  4         
  5         Return a capitalized version of S, i.e. make the first character
  6         have upper case and the rest lower case.
  7         """
  8         return ""
  9 #将首字母大写,其他变小写
 10 
 11 s = hEello World
 12 print(s.capitalize())
 13 
 14 ‘‘‘
 15 Heello world
 16 ‘‘‘
 17 
 18 
 19 def casefold(self): # real signature unknown; restored from __doc__
 20         """
 21         S.casefold() -> str
 22         
 23         Return a version of S suitable for caseless comparisons.
 24         """
 25         return ""
 26 #将字符串转换为小写
 27 
 28     def casefold(self): # real signature unknown; restored from __doc__
 29         """
 30         S.casefold() -> str
 31         
 32         Return a version of S suitable for caseless comparisons.
 33         """
 34         return ""
 35 
 36 
 37 
 38 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 39         """
 40         S.center(width[, fillchar]) -> str
 41         
 42         Return S centered in a string of length width. Padding is
 43         done using the specified fill character (default is a space)
 44         """
 45         return ""
 46 
 47 s = hello
 48 print(s.center(10,*))
 49 
 50 ‘‘‘
 51 --hello---
 52 ‘‘‘
 53 
 54 
 55 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 56         """
 57         S.count(sub[, start[, end]]) -> int
 58         
 59         Return the number of non-overlapping occurrences of substring sub in
 60         string S[start:end].  Optional arguments start and end are
 61         interpreted as in slice notation.
 62         """
 63         return 0
 64 #计数
 65 s = hello world
 66 print(s.count(s))
 67 print(s.count(o))
 68 print(s.count(o,5,10))
 69 
 70 ‘‘‘
 71 0
 72 2
 73 1
 74 ‘‘‘
 75 
 76 def encode(self, encoding=utf-8, errors=strict): # real signature unknown; restored from __doc__
 77         """
 78         S.encode(encoding=‘utf-8‘, errors=‘strict‘) -> bytes
 79         
 80         Encode S using the codec registered for encoding. Default encoding
 81         is ‘utf-8‘. errors may be given to set a different error
 82         handling scheme. Default is ‘strict‘ meaning that encoding errors raise
 83         a UnicodeEncodeError. Other possible values are ‘ignore‘, ‘replace‘ and
 84         ‘xmlcharrefreplace‘ as well as any other name registered with
 85         codecs.register_error that can handle UnicodeEncodeErrors.
 86         """
 87         return b""
 88 #转换成二进制
 89 
 90 s = 你好, world
 91 print(s.encode(encoding=utf-8))
 92 print()
 93 
 94 ‘‘‘
 95 b‘\xe4\xbd\xa0\xe5\xa5\xbd, world‘
 96 ‘‘‘
 97 
 98 
 99 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
100         """
101         S.endswith(suffix[, start[, end]]) -> bool
102         
103         Return True if S ends with the specified suffix, False otherwise.
104         With optional start, test S beginning at that position.
105         With optional end, stop comparing S at that position.
106         suffix can also be a tuple of strings to try.
107         """
108         return False
109 
110 s = hello world
111 print(s.endswith(ld))
112 print(s.endswith(lo))
113 print(s.endswith(lo,3,5))
114 
115 ‘‘‘
116 True
117 False
118 True
119 ‘‘‘
120 
121 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
122         """
123         S.expandtabs(tabsize=8) -> str
124         
125         Return a copy of S where all tab characters are expanded using spaces.
126         If tabsize is not given, a tab size of 8 characters is assumed.
127         """
128         return ""
129 #将字符串中的tab制表符转换为空格,默认为8个空格
130 
131 s = hello \t world
132 print(s.expandtabs())
133 print(s.expandtabs(20))
134 
135 ‘‘‘
136 hello    world
137 hello                world
138 ‘‘‘
139 
140 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
141         """
142         S.find(sub[, start[, end]]) -> int
143         
144         Return the lowest index in S where substring sub is found,
145         such that sub is contained within S[start:end].  Optional
146         arguments start and end are interpreted as in slice notation.
147         
148         Return -1 on failure.
149         """
150         return 0
151 #查找是否包含某个字符,不包含返回-1
152 
153 s = "hello world"
154 print(s.find(lo))
155 print(s.find(lood))
156 print(s.find(o,4,8))
157 print(s.find(o,5,8))
158 
159 ‘‘‘
160 3
161 -1
162 4
163 7
164 ‘‘‘
165 
166 
167 def format(self, *args, **kwargs): # known special case of str.format
168         """
169         S.format(*args, **kwargs) -> str
170         
171         Return a formatted version of S, using substitutions from args and kwargs.
172         The substitutions are identified by braces (‘{‘ and ‘}‘).
173         """
174         pass
175 #字符串格式化
176 
177 s = "h{0}llo w{1}rld "
178 print(s.format(e,o))
179 
180 s = "h{a}llo w{b}rld"
181 print(s.format(a=e,b=o))
182 
183 
184 
185 def format_map(self, mapping): # real signature unknown; restored from __doc__
186         """
187         S.format_map(mapping) -> str
188         
189         Return a formatted version of S, using substitutions from mapping.
190         The substitutions are identified by braces (‘{‘ and ‘}‘).
191         """
192         return ""
193 #字符串格式化
194 
195 s = hello w{k1}rl{k2}
196 print(s.format_map({k1:o,k2:d}))
197 
198 
199 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
200         """
201         S.index(sub[, start[, end]]) -> int
202         
203         Return the lowest index in S where substring sub is found, 
204         such that sub is contained within S[start:end].  Optional
205         arguments start and end are interpreted as in slice notation.
206         
207         Raises ValueError when the substring is not found.
208         """
209         return 0
210 #查找下标
211 s = "hello world"
212 print(s[0:5])
213 print(s.index(o))
214 print(s.index(o,4,20))
215 print(s.index(o,5,10))
216 print(s.index(lo))
217 # print(s.index(‘p‘))  #不存在则会报错ValueError: substring not found
218 
219 
220 def isalnum(self): # real signature unknown; restored from __doc__
221         """
222         S.isalnum() -> bool
223         
224         Return True if all characters in S are alphanumeric
225         and there is at least one character in S, False otherwise.
226         """
227         return False
228 #判断字符串是否都是数字或者字母组成
229 
230 s = helloworld
231 s1 = 1234
232 s2 = hel123
233 s3 = 12 he
234 s4 = \t
235 print(s.isalnum())
236 print(s1.isalnum())
237 print(s2.isalnum())
238 print(s3.isalnum())
239 print(s4.isalnum())
240 
241 ‘‘‘
242 True
243 True
244 True
245 False
246 False
247 ‘‘‘
248 
249 
250 
251 def isalpha(self): # real signature unknown; restored from __doc__
252         """
253         S.isalpha() -> bool
254         
255         Return True if all characters in S are alphabetic
256         and there is at least one character in S, False otherwise.
257         """
258         return False
259 #判断字符串是否是字母组成
260 
261 s = hello world
262 s1 = 134he
263 s2 = 234
264 s3 = helloworld
265 print(s.isalpha())
266 print(s1.isalpha())
267 print(s2.isalpha())
268 print(s3.isalpha())
269 
270 ‘‘‘
271 False
272 False
273 False
274 True
275 ‘‘‘

 

Python数字、字符串

标签:highlight   cas   ndt   pre   end   ignore   说明   格式化   二进制   

原文地址:https://www.cnblogs.com/jmwm/p/9643951.html


评论


亲,登录后才可以留言!