Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python binary search + string template + textwrap Module

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today Xiaobian to share with you about Python binary search + string template + textwrap module instance analysis of the relevant knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you will learn something after reading this article, let's take a look at it.

Binary search

The problem scenario is in an ascending array (which is actually a list of only integers), looking for the subscript of a target number, and there is no return of-1.

The solution is because the array is in ascending order, so the binary search can first take out the intermediate value in the array, compare it with the target number, determine half of the range, and then repeat the above steps to narrow the range.

The code is as follows:

Def search (nums, start, end, target): if start > end: return-1 # get the intermediate value mid = (start + end) / / 2 # compare the relationship between the median value and the target number if nums [mid] > target: # the median value is greater than the target data, and the number of targets on the left return search (nums, start, mid, target) if nums [mid] = target: # the median is equal to the target data Return return mid if nums [mid]

< target: # 中值小于目标数据,目标数在右侧 return search(nums, mid, end, target)if __name__ == '__main__': ret = search([1, 2, 3, 4], 0, 4, 1) print(ret)字符串模板 问题场景 + 拼接字符串会让代码变得难以阅读,是否存在其它办法可以将字符串进行格式化? 解决思路 Python 字符串允许出现占位符,然后再通过特定的代码将占位符替换掉。 编码如下: import stringtp1 = string.Template('你正在阅读$name的博客')tp2 = string.Template('你正在阅读${name}的博客')s1 = tp1.substitute(name="橡皮擦")s2 = tp2.substitute(name="橡皮擦")print(s1)print(s2) 其中 $ 是占位符开头的特殊符号,如果字符串本身也存在 $ 符号,需要使用 $$ 代替。 字符串模板使用的是 string 模块中的 Template 类,替换字符串需要调用对象的 substitute() 方法。 需要特别注意的是如果 substitute() 方法中的参数数量与模板中不一致,Python编译器也不会抛出错误。 import stringtp1 = string.Template('你正在阅读$name的博客')s1 = tp1.substitute(name="橡皮擦", age=18) # 参数不一致,不会出现错误print(s1) 但反之如果字符串模板中存在一个占位符,但是 substitute() 方法中没有提供,就会抛出异常。 import stringtp1 = string.Template('你正在阅读$name的博客')tp2 = string.Template('你正在阅读${name}$age的博客')s1 = tp1.substitute(name="橡皮擦", age=18) # 参数不一致,不会出现错误s2 = tp2.substitute(name="橡皮擦") # 但是这样确发生错误s3 = tp2.safe_substitute(name="橡皮擦")print(s1)print(s2)print(s3) 解决上述问题的办法,就是使用 字符串模板类中提供的另一个 safe_substitute() 方法,代码如下 import stringtp1 = string.Template('你正在阅读$name的博客')tp2 = string.Template('你正在阅读${name}$age的博客')# s2 = tp2.substitute(name="橡皮擦") # 但是这样确发生错误s3 = tp2.safe_substitute(name="橡皮擦") # 不会报错# print(s2)print(s3)textwrap 模块 问题场景 Python中可以对文本,即字符串进行更加细致的操作,例如自动换行,填充字符。 解决思路 使用 textwrap 模块进行操作。 首先使用 help() 函数查看该模块具有哪些类与方法。 模块内具备类 TextWrapper(builtins.object) ,具备如下方法: dedent(text):移除 text 中每一行的任何相同前缀空白符; fill(text, width=70, **kwargs):将单个段落包装在 text 中,并返回包含已包装段落的单个字符串,fill() 和 wrap() 方法类似,分割结果相同,但返回结果形式不同,它的作用就是在分割的片段之间添加 \n ,然后将其重新变成一个文本进行输出; indent(text, prefix, predicate=None):将 prefix 添加到 text 中选定行的开头; shorten(text, width, **kwargs):在 text 中截取给定 width 的字符; wrap(text, width=70, **kwargs):将 text 中的单个段落(字符串)换行,每一行最多为 width 个字符长。返回输出行列表,不带最终换行符。 编码如下 textwrap.wrap() import textwraptext = "你好, 我是橡皮擦 这是Python学习的第2天"result = textwrap.wrap(text,10)print(result) 输出结果如下: textwrap.fill() import textwraptext = "你好, 我是橡皮擦 这是Python学习的第2天"result = textwrap.fill(text,10)print(result) textwrap.dedent(text) 该方法可以移除不需要的前缀空格。可以用来使三引号的字符串与显示的左边缘对齐,同时仍然以缩进的形式在源代码中显示。 import textwraptext = ''' 大家好 我是橡皮擦 这是大家的Python博客'''print(text)print("*"*100)print(textwrap.dedent(text)) 运行结果如下: textwrap.indent() import textwrapsample_text = ''' 你好,我是橡皮擦 这是我的博客 写作的内容都是 Python 希望得到你的关注 '''dedented_text = textwrap.dedent(sample_text)final = textwrap.indent(dedented_text, '>

') print (final)

The running results are as follows:

Count the number of phrases according to spaces

A paragraph of the problem scenario, such as "I'm an eraser, this is everyone's Python blog", counts how many phrases there are.

The way to solve the problem is to judge that the first character of the character is a space.

The code is as follows

Class Ca: def phrase_count (self P): C = 0 # count for i in range (len (p)): # if the current character is not a space and is not the first bit or the previous character is not a space if p [I]! =''and (I = = 0 or p [I-1] = =''): # plus 1 C + = 1 return cif _ name__ = ='_ main__': c = Ca () p ='I am an eraser This is everyone's Python blog 'print (the number of phrases is: {c.phrase_count (p)} ") fill the string with" 0 "

The problem scenario populates the placeholder 0 in front of the string.

The solution uses the zfill () method to return a string of specified length, with the original string aligned to the right, preceded by 0.

Coding time

Str = "Eraser's blog" print (str.zfill (20)) print (str.zfill (30))

These are all the contents of the article "Python binary search + string template + textwrap module example analysis". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report