Introduction to strings in python (Part 1)

Xiaobo test growth path 2021-10-29 01:28:18
introduction strings python

The last chapter introduced python Keywords in 、 Variable 、 Input and output 、 notes 、 There are also concepts such as data types , The following article mainly introduces python Notes on strings in . The article only lists the key knowledge points according to what I think , I won't list particularly detailed points .

String definition : Pairs of single quotes or pairs of double quotes 、 The character content enclosed in three quotation marks .

String index : Every letter in the string is indexed , The index is the position corresponding to each character , What is the order of indexes 2 Kind of :

positive sequence : Left to right index default 0 At the beginning , The maximum range is less string length 1

trans : Right to left index default -1 At the beginning , The maximum range is at the beginning of the string

String escape

You can use a backslash to escape , such as \n Means line break ,\t Represents a tab , Use r You can keep the backslash from escaping .

a = "hello\tworld"
b = r"hello\tworld"
Print respectively a and b Value :
hello world
hello\tworld

Concatenation and repetition of strings

Strings can be used + Splicing

have access to * No. print duplicate string

a = 'ac'
b = 'ad'
print(a+b)
print(a*3)

The value of the string cannot be changed , You cannot directly change the value of a character in a string

such as , Defines a string ,name=' Xiaobo ', When trying to change the first character of a string ,name[0]=' Li ' , Implementation will report TypeError: 'str' object does not support item assignment In the wrong , explain , The value of the string is not allowed to be changed .

that , Why is there no error when you re assign a value to a string variable ? Use name=‘'xxx' It actually points to a new string .

have access to id() Function to verify the effect :

name = 'xiaobo'
print(id(name))
name = 'libo'
print(id(name))
Printed id It's different 

Although it can't be modified directly , However, you can indirectly modify the value of the string , Get a new string :

name = ' Xiaobo '
print(id(name))
name1=name.replace(' Small ',' Li ')
print(id(name1))
But printed out id The value is completely different 

String interception ( section )

A complete slice expression :str[start_index:end_index:step]

step: Either positive or negative , Its absolute value determines the ‘‘ step ”, and The sign determines “ Cut the direction ”, It means “ From left to right ” Value , Negative representation “ From right to left ” Value . When step When omitted , The default is 1, From left to right in steps 1 Value .

start_index: Indicates the starting index ( Contains the corresponding value of the index ); When this parameter is omitted , To represent a subordinate “ Endpoint ” Start taking value , As for from “ The starting point ” Or from the “ End ” Start , By step The positive and negative determination of parameters ,step From “ The starting point ” Start , For the negative from “ End ” Start .

end_index: Indicates that the index is terminated ( Does not contain the corresponding value of the index , It is similar to the open interval in mathematics ); When this parameter is omitted , It means to fetch data all the way to “ Endpoint ”, As for the arrival of “ The starting point ” Or to “ End ”, By the same step The positive and negative determination of parameters ,step Set the timing until “ End ”, It's negative until “ The starting point ”.

name = 'hello world'
print(name[0:5:1], name[:5:]) #hello hello
print(name[::]) #hello world
print(name[::-1]) #dlrow olleh

Determine whether the string meets some format requirements

print('123'.isdigit())# Returns... For a pure number True, Otherwise return to False
print('NAME'.isupper())# Returns... For pure uppercase letters True, Otherwise return to False
print('name'.islower())# Returns... For pure lowercase letters True, Otherwise return to False
print(' '.isspace())# Returns... When it is a pure space True, Otherwise return to False
print('sdfjklsdjkflsdjl'.isalpha())# Returns... If it is a pure letter True, Otherwise return to False
print('sadsfj23423423'.isalnum())# Returns... When it is a letter or number Ture, Otherwise return to False
Above is python Some off the shelf methods provided , Regular expressions can be used for other format verification 

Use scenarios :

1、 When doing projects in the future , Do some input verification , For example, the verification password can only be letters or numbers , If it meets the requirements, print True, Print if it does not meet the requirements False

Printing of strings

Use % Format the output :

print("my name is %s" % ("xiaobo"))
print("my name is %.2s" % ("xiaobo")) # String interception %.2s Retain 2 A string of length
print("my age is %d" % (29.2)) # Output integer %d
print("my salaly is %f" % (29)) # Output floating point number %f
print("my height is %f m" % (1.73))
print("my height is %.2f m" % (1.73)) # Specify the number of output decimal places %.3f ( Keep it after the decimal point 3 position )
The output results correspond to the following :
my name is xiaobo
my name is xi
my age is 29
my salaly is 29.000000
my height is 1.730000 m
my height is 1.73 m

Use format Function to format the output :

Relative to the basic format output using ‘%’ Methods ,format() More powerful , This function treats the string as a template , Format with the parameters passed in , And use curly braces ‘{}’ Instead of a special character ‘%’.

Usage method :

  • No serial number is specified , Auto match {}{}
  • Specify the sequence number to match {0}{1}
  • Specify the same sequence number to match {1}{1}
  • Specify sequence number + Format the output to match {0:d}{1:.2f}, Note that there should be no space between the serial number and colon
  • Appoint key The way to match {name}{age}
  • Appoint key+ Format the output to match {0:d}{1:.2f}, it is to be noted that key There must be no spaces between and colons

Use cases :

print("my name is {},age is {}".format("xiaobo", 29))
print("my name is {0},age is {0}".format("xiaobo", 29))
print("my name is {0},age is {1}".format("xiaobo", 29))
print("my name is {0},age is {1},height is {2:.2f}".format("xiaobo", 29, 173))
print("my name is {name},age is {age},height is {height:.2f}".format(height=173, age=29, name="xiaobo"))
print("my name is {name:s},age is {age:d},height is {height:.3f}".format(height=173, age=29, name="xiaobo"))
The corresponding outputs are as follows :
my name is xiaobo,age is 29
my name is xiaobo,age is xiaobo
my name is xiaobo,age is 29
my name is xiaobo,age is 29,height is 173.00
my name is xiaobo,age is 29,height is 173.00
my name is xiaobo,age is 29,height is 173.000

The format controller of the string and its description are shown in the following table . The format control is after the placeholder index or placeholder name , Use a colon between Partition , grammar :{ Parameter number : Format controller } or { Parameter name : Format controller }.

The format controller of the string and its description are shown in the following table :

More highlights , You can click on the official account menu or enter group chat , Communicate and learn with your friends .

This article is from WeChat official account. - Xiaobo's road to growth (libotest) , author : Xiaobo knowledge sharing

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2021-09-16

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Xiaobo test growth path]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013131552390E.html

  1. J'espère que quelqu'un peut m'aider.
  2. Quelqu'un peut écrire du Code en python?
  3. Dataframe数据,用pandas.to_excel导出成excel问题
  4. Données du cadre de données, en utilisant pandas.to Exporter Excel vers un problème Excel
  5. 请问这个过期的要怎么弄呀,Python是下载的3.10版本的
  6. 請問這個過期的要怎麼弄呀,Python是下載的3.10版本的
  7. Qu'est - ce qu'on fait de ce vieux python?
  8. Python数据处理转置问题??
  9. Problèmes de transposition du traitement des données python??
  10. 使用python的pdfkit把html转pdf时,echarts无法显示
  11. python利用3维的0,1矩阵再matplotlib中画图
  12. Pycham developing Django project template tutorial
  13. Libraries commonly used in Python data analysis
  14. Python utilise une matrice tridimensionnelle 0, 1 pour redessiner les graphiques dans matplotlib
  15. 预备知识-python核心用法常用数据分析库(上)
  16. 預備知識-python核心用法常用數據分析庫(上)
  17. 我在python上创建了个web静态服务器,把一个前端页面,放进去然后在静态服务器上访问只出现了前段页面的代码,代码运行正常,这是怎么回事
  18. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅰ)
  19. 预备知识-python核心用法常用数据分析库(上)
  20. J'a i créé un serveur Web statique sur Python, j'ai mis une page frontale, j'ai accédé au Code sur le serveur statique qui n'avait que des pages frontales, et le Code fonctionnait correctement
  21. 预备知识-python核心用法常用数据分析库(下)
  22. python 文件排版,怎么控制写入在对应文件的位置(要写吐了,真是服了)
  23. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅰ)
  24. Typographie de fichiers Python, comment contrôler l'écriture à l'emplacement du fichier correspondant (pour écrire et vomir, vraiment pris)
  25. python:例题求解,不知道怎么等输入完所有数字后再输出
  26. 用python来实现:根据实际查询结果补充完整数据
  27. Mise en œuvre en python: compléter les données complètes en fonction des résultats réels de la requête
  28. python对excel进行分组但不进行聚合统计操作,且输出到不同的表格中?
  29. Python regroupe Excel, mais n'effectue pas de statistiques agrégées, et l'affiche dans différents tableaux.
  30. python如何提交,不要用太复杂的函数
  31. Comment soumettre Python sans utiliser de fonctions trop complexes
  32. Python,数据文件操作问题,想要代码
  33. python 提取多个字符串中的多个字段
  34. python 读入用户输入的一组正整数,到-1结束
  35. Python lit un ensemble d'entiers positifs entrés par l'utilisateur, se terminant par - 1
  36. 测试逐飞的MM32F3277 MicroPython开发板的基本功能
  37. Python timer reference
  38. 关于#python#的问题:python3队列维护
  39. Developing Hongmeng equipment program using python (3-prototype of security system)
  40. Questions sur # # Python #: maintenance de la file d'attente Python 3
  41. 怎么用Python打印数字三角
  42. 怎麼用Python打印數字三角
  43. Comment imprimer un triangle numérique en python
  44. Tester la fonctionnalité de base du tableau de développement microspython mm32f3277 Flying - by - flying
  45. Python extrait plusieurs champs de plusieurs chaînes
  46. Pandas核心用法
  47. Utilisation centrale de pandas
  48. Python, problème de fonctionnement du fichier de données, Code désiré
  49. 【78技术人社群~Python分部】,就在今天成立 →
  50. 社区共读《Python编程从入门到实践》第一天阅读建议
  51. La communauté lit les recommandations de lecture pour la première journée de la programmation Python de l'introduction à la pratique
  52. [78 Communauté des technologues ~ Division Python], fondée aujourd'hui →
  53. Pandas核心用法
  54. 您好,请问您的python按钮开了线程处理还卡ui的问题解决了吗
  55. Python: résolution d'exemples, je ne sais pas comment attendre que tous les chiffres soient entrés avant de sortir
  56. Bonjour, puis - je vous demander si votre bouton Python est activé pour le traitement du thread et le retour de l'interface utilisateur de la carte a été résolu?
  57. Utilisation centrale de pandas
  58. Python technique 2: advanced usage of function parameters
  59. OpenCV-Python实战(14)——人脸检测详解(仅需6行代码学会4种人脸检测方法)
  60. OpenCV-Python實戰(14)——人臉檢測詳解(僅需6行代碼學會4種人臉檢測方法)