search
HomeBackend DevelopmentPython TutorialWhat are the python character types?

What are the python character types?

What are the character types in python? Let me introduce to you the types of character types:

String

Definition: a = 'Python' a = '123' a = "Python" a = """123""" a = '''Python''' There is no difference between single quoting, double quoting and triple quoting for strings. Those with special meanings are not converted. If you need to output the data in quotation marks normally, add r directly in front of it as follows:

   print("a\nb") Output: a and b (note: here is Line wrapped)

Print(r"a\nb") Output: a\nb (Note: r means no escaping)

Print('i'm Python') Error report .Reason: The program is considered to be over when it reaches the second '. m will be treated as a variable, but it is not a variable here, so an error is reported. The correct way to write it is as follows:

print("i'm Python") Anything containing letters needs to be quoted. Otherwise, an error will be reported.

Related recommendations: "python video tutorial"

String built-in methods

#定义变量
msg = "i'm YHL"
  
    capitalize()           注解:首字母大写. 如:已经大写还是大写 其他大写变成小写
print (msg.capitalize())  
输出:I'm yhl
  
  lower()                 注解:将大写字母转成小写
print(msg.lower())        
输出:i'm yhl
  
  upper()                 注解:将所有小写转成大写
print(msg.upper())        
输出:I'M YHL
  
  center(长度,填充的值)     注解:定义长度.让其变量中字符串剧中显示
print (msg.center(20))    
输出:      i'm YHL       :
print (msg.center(20,"*"))
输出:******i'm YHL*******
  
  count("值")              注解:统计某一字符串出现的次数
print (msg.count("Y"))    
输出:1
print (msg.count("Y",0,3))
输出:0     PS:从下标开始找. 下标0-3之间找Y出现过几次.  注意:顾头不顾尾.这里是0-3实际是0-2
print (msg.count("Y",0,-1))
输出:0     PS:从下标开始找. 下标0--1之间找Y出现过几次. 注意:此处的-1表示最后
print (msg.count("Y",3))  
输出:1     PS:从下标开始找. 下标3之后开始找Y出现过几次.
  
  endswith("值")            注解:判断以什么结尾.真返回True  否则返回Fales
print (msg.endswith("d")) 
输出:False PS:意思是以什么结尾.如果是返回True 否则返回False 
  
=====================================================================================================================
#定义变量    PS:变量中的\t表示空格.默认是一个tab键
msg1 = "a\tb"
  
  xpandtabs()                注解:设置空格大小.默认是八个空格.意思就是说括号中不写数字
print(msg1.expandtabs(10))
输出:设置a and b之间的空格大小.
  
  find("值")                 注解:查找字符下标或坐标.注意:\t默认占1位.键盘上空格敲1下占1位.敲2下占2位.以此类推.一个tab键就占1位
print(msg1.find("b"))
输出:2    PS:空格也算.  注意:如果找不到会返回-1
print(msg1.find("b",0,8))           
输出:2    PS:如果字符串中出现多个只回显第一个的下标.还有就是这样写是规定一个范围
  
  format("值","值")           注解:格式化字符串
print("{0}{1}{0}".format("name","age"))  
输出:nameagename  ps:{0}-name{1}-age{0}-name 注意:相当于是下标一一对应
print("{name}".format(name="YHL"))     
输出:YHL      ps:相当于打印变量name对应的值.
print("{}{}{}".format("name","age","YHL")) 
输出:nameageYHL   ps:前边中括号有几个后台值就必须有几个.否则会报错. 注意括号不能多.值可以多
  
  index("值")                  注解:查找索引
print(msg1.index("a"))            
输出:1              PS:如果一个变量中出现多个相同的字母.那么也只返回第一个
  PS:find 和 index 都是查找下标.
  两个的区别在于:
    find:是不知道有没有.是去找. 如果有正常返回.如果没有返回-1
    index:是知道有.通过已知的去找对应的下标.  如果有正常返回.如果没有直接报错
  
=====================================================================================================================
#定义变量  
msg2 = "a123"
  
  isalnum()                    注解:判断变量是否由数字和字母组成.是返回True.否则返回False  纯数字和纯字母都可以.不能是数字和字母之外的
print(msg2.isalnum())     
输出:True
  
  isalpha()                    注解:是字母返回True  否则返回False. 必须全是字母
print(msg2.isalpha())     
输出:False
  
=====================================================================================================================
#定义变量
msg3 = "10"
  
  isdecilmal()                 注解:判断是否是十进制数. 是返回True 否则返回False   注意:只能是数字.
print(msg3.isdecimal())   
输出:True     PS:如果是10.2则会报错.
  
  isdigit()                    注解:判断是不是整型    注意:只能整数.
print(msg3.isdigit())     
输出:True
  
=====================================================================================================================
#定义变量
msg4 = "if"
  
  isidentifier()               注解:判断字符串中是否存在关键字. 是返回True 否则返回False
print(msg4.isidentifier())
输出:True     PS:如果是ifa的话就直接返回True  一定要清楚是关键字.(包含)
  
  islower()                    注解:判断字符串是否为小写. 是返回True 否则返回False
print(msg4.islower())     
输出:True     PS:必须全都是小写. 否则返回False
  
  isupper()                    注解:判断字符串是否为大写. 是返回True 否则返回False
print(msg4.isupper())     
输出:False    PS:必须全都是大写. 否则返回False
  
=====================================================================================================================
#定义变量
msg5 = " "
  
  isspace()                    注解:判断是否为空格.是空格返回True 否则返回False. 注意:\t也是空格. tab  \n  敲键盘空格一样
print(msg5.isspace())     
输出:True     PS:不能有其他的.必须全是空格
  
=====================================================================================================================
#定义变量
msg6 = "Hello Word"
  
  istitle()                     注解:判断抬头.  就是首字母是不是大写.是就返回True.  否则返回False.
print(msg6.istitle())     
输出:True     PS:是单词的首字母.如果单词中还有别的是大写也是False
  
=====================================================================================================================
#定义变量
msg7 = "Yhl"
  
  ljust(值,"*")                  注解:左对齐.
print(msg7.ljust(10,"*")) 
输出:Yhl*******   PS:左对齐,缺少的部分用*填充.长度是10
print(msg7.ljust(10))     
输出:Yhl          PS:左对齐,缺少的部分用空格填充.长度是10
  
  ljust(值,"*")                  注解:右对齐.
print(msg7.rjust(10,"*")) 
输出:*******Yhl   PS:右对齐,缺少的部分用*填充.长度是10
print(msg7.rjust(10))     
输出:       Yhl   PS:右对齐,缺少的部分用空格填充.长度是10
  
=====================================================================================================================
#定义变量
msg8 = "  abcd  "
  
  strip()                        注解:去掉空格(前后都去). 如果:"  SA  SAS"那么中间的空格无法去除
print(msg8.strip())       
输出:abcd
  
  lstrip()                       注解:只去掉左边的空格.右边的不去掉
print(msg8.lstrip())      
输出:abcd  "
  
  rstrip()                       注解:只去掉右边的空格.左边的不去掉
print(msg8.rstrip())      
输出:  abcd
  
  maketrans("值","值")             注解:制作翻译表.下边是用法.   长度必须是一一对应否则会报错.
msg9 = "my name is abcd"
table = str.maketrans("a","2")
print(msg9.translate(table))
输出:my n2me is 2bcd
  
=====================================================================================================================
#定义变量
msg10 = "abcdefg"
  
  zfill(10)                       注解:右对齐.左边不够的用0填充
print(msg10.zfill(10))
输出:000abcdefg
python 字符串相关方法

Common string operations

1.移除空白
    msg01 = "   dsadasi21 \n  "
    print(msg01.strip())      
    输出:dsadasi21
      
2.分割
    msg02 = "www.baidu.com"
    print(msg02.split("i"))
    输出:['www.ba', 'du.com']    PS:以i为点进行分割.
      
    print(msg02.split(".",1))
    输出:['www', 'baidu.com']    PS:以.进行分割1次.
      
    print(msg02.split(".",2))
    输出:['www', 'baidu', 'com'] PS:以.进行分割2次. 注意:如果.在字符串中不够分的次数.那么不会报错.按最多分
      
    print(msg02.split(".")[0])
    输出:www                     PS:以.进行分割.并打印出下标为0的数据
      
    print(msg02.split(".")[-1])
    输出:com                     PS:以.进行分割.并打印出最后一个数据
      
    print(msg02.split(".")[0:2])
    输出:['www', 'baidu']        PS:以.进行分割.并打印出下标是0,1的数据
      
3.长度
    msg03 = "www.baidu.com"
    print(len(msg02))
    输出:13       PS:计算字符串长度
      
4.索引(和切片很像)
    msg04="welcometobeijingYhl"
    print(msg04[2])
    输出:l        PS:通过索引获取字符串中对应的值
    print(msg04.index("o"))
    输出:4        PS:通过字符串中的值找对应的下标(索引)
  
5.切片
    msg04="welcometobeijingYhl"
    print(msg04[0:3])
    输出:wel
      
    print(msg04[0:])
    输出:welcometobeijingYhl
      
    print(msg04[0:-1])
    输出:welcometobeijingYh
      
    print(msg04[:])
    输出:welcometobeijingYhl
      
    print(msg04[2])
    输出:l                        PS:通过索引取对应的值
      
    print(msg04[2:7:2])
    输出:loe                      PS:步长. 各几个取几次. 

The following table is a list of non-printing characters that can be represented by escape or backslash symbols.

Note: In doublequoted strings, escape characters are interpreted; in singlequoted strings, escape characters are preserved.

What are the python character types?

String operators

Suppose A holds the string variable 'hello' and variable b holds 'Python':

What are the python character types?

Evil string splicing:

The string in python is represented as a character array in C language, each When you create a string for the first time, you need to open up a continuous space in the memory, and once you modify the string, you need to open up a new continuous space again. Every time the evil plus sign ( ) appears, it will be re-opened in the memory. Create a new space.

The following is a complete list of the complete set of available symbols:

What are the python character types?

Other supported symbols and functions are listed in the following table:

What are the python character types?

The above is the detailed content of What are the python character types?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)