Home Backend Development Python Tutorial Example explanation of Character string in python

Example explanation of Character string in python

Sep 25, 2017 am 11:25 AM
character python string

The following editor will bring you an article on Character string in python (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look

1. Python string

String is the most commonly used data type in Python. We can use quotation marks (' or ") to create strings. l

Python does not support single character types, and single characters are also used as a string in Python.


>>> var1 = 'hello python' #定义字符串
>>> print(var1[0]) #切片截取,从0开始,不包括截取尾数
h
>>> print(var1[0:5])
hello
>>> print(var1[-6:])
python
>>> var2 = var1[0:6]+'world' #截取字符并拼接赋值给新变量
>>> print(var2)
hello world
Copy after login

2. Python escape character

\ : At the end of the line, it is the line continuation character

\\ : Backslash escape, output '\'

\' :Single quote escape

\":Double quote escape

\b :Backspace

\n :Line feed

\v :Vertical tab character

\t :Horizontal tab character

\r :Carriage return

\f :Page change

3. Python string operators

(+) splicing, (*) repetition, ( []) index, ([:]) slicing, (in) member judgment, (not in) non-member judgment, (r/R) element output string


>>> var1 = 'hello'
>>> var2 = 'python'
>>> print(var1+var2) #拼接字符串
hellopython
>>> print(var1*3) #重复输出字符串
hellohellohello
>>> print(var1[0]) #索引字符串
h
>>> print(var1[3:]) #索引切片
lo
>>> 'e' in var1 #判断字符串是否在变量中
True
>>> 'p' not in var1 #判断字符串是否不在变量中
True
>>> print("he\tllo \n") 
he llo 
>>> print(r"he\tllo \n") #原始输出字符串,也就是原始输出转义字符
he\tllo \n
Copy after login

4. Formatted strings

Python supports the output of formatted strings. Although this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %s.

In Python, string formatting uses the same syntax as the sprintf function in C.

Python string formatting symbols:

%cFormatting characters and their ASCII codes
%sFormat string
%dFormat integer
%uFormat unsigned integer
%oFormat unsigned octal number
%xFormat unsigned hexadecimal number
%XFormat unsigned hexadecimal number System number (uppercase)
%fFormat floating point numbers, you can specify the precision after the decimal point
%eUse scientific notation to format floating point numbers
%EThe function is the same as %e, use scientific notation to format floating point numbers
%gAbbreviation of %f and %e
%GAbbreviation of %f and %E
%pFormat the address of a variable as a hexadecimal number

Format operator Auxiliary instructions:

*Define width or decimal point precision
-Used for left alignment
+Display plus sign (+) in front of positive numbers
Display spaces before positive numbers
#Display zero ('0') before octal numbers, before hexadecimal numbers Display '0x' or '0X' (depending on whether 'x' or 'X' is used)
0The displayed number is filled with '0' in front and Instead of the default space
%'%%' outputs a single '%'
(var)Map variable (dictionary parameter)
m.n.m is the minimum total width of the display, n is the number of digits after the decimal point (if available)


##

>>> print("ascii:%c"%'s') #格式化输出字符
ascii:s
>>> print("ascii:%c"%'1') #格式化输出数字
ascii:1
>>> print("str:%s"%'character string') #格式化字符串
str:character string
>>> print("str:%d"%888) #格式化整数
str:888
>>> print("str:%f"%888) #格式浮点数
str:888.000000
>>> print("str:%e"%888) #格式化科学计数浮点数
str:8.880000e+02
>>> print("str:%E"%888) #同上
str:8.880000E+02
>>> print("str:%G"%888) #%f和%E的简写
str:888

>>> print("str:%20f"%888.089) #定义20宽度输出
str:  888.089000
>>> print("str:%-20f"%888.089) #用左对齐
str:888.089000  
>>> print("str:%+20f"%888.089) #在正数前显示加号
str:  +888.089000
>>> print("str:%+-20f"%888.089) #左对齐显示加号
str:+888.089000  
>>> print("str:%020f"%888.089) #以0填充默认的空格
str:0000000000888.089000
>>> print("str:%%%20f"%888.089) #在数字前输入%号
str:%  888.089000
>>> print("str:%%%-20f"%888.089) #左对齐输出%号
str:%888.089000  
>>> print("str:%20.3f"%888.089) #显示最小总宽度20,小数点后位数为3位
str:  888.089
Copy after login

Since python2.6, the format string function str.format():

usage has been added : It uses {} and : to replace %

Positional parameters are not subject to order constraints, and can be {} empty, as long as there is a corresponding parameter value in the format. If the parameter value is not enough, an error will be reported. The parameter index starts from 0, and the incoming positional parameter list can be *list


In [27]: '{}+{}={}'.format(1,2,3) #格式化按顺序应用参数值
Out[27]: '1+2=3'
In [28]: '{2}-{1}={0}'.format(1,2,3) #指定顺序应用参数值
Out[28]: '3-2=1'
In [29]: '{0}+{0}={1}'.format(2,3) #指定参数可以重复使用
Out[29]: '2+2=3'
In [30]: '{}+{}={}'.format(2,3) #如不指定顺序,format参数不够就会报错
---------------------------------------------------------------------------
IndexError    Traceback (most recent call last)
<ipython-input-30-29f40e412920> in <module>()
----> 1 &#39;{}+{}={}&#39;.format(2,3)
IndexError: tuple index out of range

In [31]: l1 = [2,4,8] 
In [32]: &#39;{}*{}={}&#39;.format(*l1) #使用列表引用参数值
Out[32]: &#39;2*4=8&#39;

In [33]: dct = {&#39;name&#39;:&#39;python&#39;,&#39;age&#39;:20} #定义字典
In [35]: &#39;welcom to {name},age is {age}&#39;.format(name=&#39;qi&#39;,age=28) #变量引用
Out[35]: &#39;welcom to qi,age is 28&#39;

In [36]: &#39;welcom to {name},age is {age}&#39;.format(**dct) #使用**引用字典参数必须填写key值
Out[36]: &#39;welcom to python,age is 20&#39;

填充与格式化:
In [53]: "{0: >20}".format("string") #从0位开始已空格填充20宽度左对齐
Out[53]: &#39;  string&#39;

In [54]: "{0:&>20}".format("string")
Out[54]: &#39;&&&&&&&&&&&&&&string&#39;

In [55]: "{0:#>20}".format("string") #使用#号会有个小bug
 ....: 
Out[55]: &#39;##############string&#39;

In [60]: &#39;{0:+<20}&#39;.format("string") #向右对齐填充+
Out[60]: &#39;string++++++++++++++&#39;

In [61]: &#39;{0:+^20}&#39;.format("string") #剧中对齐填充+
Out[61]: &#39;+++++++string+++++++&#39;

精度与进制:
>>> &#39;{0:.3f}&#39;.format(10/3) #小数位进度格式化
&#39;3.333&#39;
>>> &#39;{0:b}&#39;.format(8) #格式化二进制
&#39;1000&#39;
>>> &#39;{0:o}&#39;.format(9) #格式化八进制
&#39;11&#39;
>>> &#39;{0:x}&#39;.format(26) #格式化十六进制
&#39;1a&#39;
>>> &#39;{0:,}&#39;.format(123456789) #千分位格式化
&#39;123,456,789&#39;

使用索引:
>>> l2 = [&#39;AA&#39;,{&#39;bb&#39;:&#39;cc&#39;},(&#39;d&#39;,&#39;e&#39;)] #列表索引引用
>>> &#39;outing:{0[0]}&#39;.format(l2) 
&#39;outing:AA&#39;
>>> &#39;outing:{0[0]},{0[1]}&#39;.format(l2) #将列表当成一个元素,在其中索引值
"outing:AA,{&#39;bb&#39;: &#39;cc&#39;}"
Copy after login

5. Python's string method


>>> s = &#39;i mi to&#39; #将字符串的第一个字符改为大写
>>> s.capitalize()
&#39;I mi to&#39;

>>> s = &#39;I MI TO&#39; #将字符串所有字符改为小写
>>> s.casefold()
&#39;i mi to&#39;

>>> s.center(15) #将字符串剧中,并用空格将字符串填充长度,如指定长度小于实际长度则没有效果
&#39; I MI TO &#39;

>>> s = &#39;abcabcabcabc&#39; #返回sub在字符串里出现的次数,start,end为可选参数,决定范围
>>> s.count(&#39;a&#39;,0,12)
4
>>> s.encode(encoding=&#39;utf-8&#39;,errors=&#39;strict&#39;) #以encoding指定的编码格式对字符串进行编码
b&#39;abcabcabcabc&#39;
>>> s.endswith(&#39;abc&#39;,1,12) #检查字符串是否以sub结尾,是返回True,否返回False,start,end为可选参数,决定范围
True

>>> s = &#39;a\tb\tc&#39;
>>> s.expandtabs(4) #把字符串的tab字符(\t)转化为空格,如不指定tabsize,默认为8个空格
&#39;a b c&#39;

>>> s.find(&#39;b&#39;) #检测字符串是否在字符串中,如在则返回索引,否则返回-1,可指定起始值。
2

>>> s=&#39;hello python&#39;
>>> s.index(&#39;hello&#39;) # 类似find(),不同在于如果sub不在字符串中,返回异常
0 

>>> s.isalnum() #有空格返回false
False
>>> s=&#39;hellopython&#39;
>>> s.isalnum() #如果字符串至少有一个字符,并且所有字符都是字母或数字则返回True,否则False
True
>>> s.isalpha() #如果字符串至少有一个字符,并且所有字符都是字母则返回True,否则False
True

>>> s = &#39;123&#39;
>>> s.isdigit() #如果字符串只包含数字则返回True,否则返回False
True

>>> s = &#39;123&#39;
>>> s.isdecimal() #如果字符串只包含十进制数字则返回True,否则返回False
True
>>> s= &#39;ox123&#39;
>>> s.isdecimal()
False
>>> s = &#39;0.33&#39;
>>> s.isdecimal()
False

>>> s = &#39;abc&#39;
>>> s.islower() #如果字符中至少包含一个能区分大小写的字符,并且这些字符都是小写则返回True,否则返回Flase
True
>>> s = &#39;Abc&#39;
>>> s.islower()
False

>>> s = &#39;ABC&#39;
>>> s.isupper() #果字符中至少包含一个能区分大小写的字符,并且这些字符都是大写则返回True,否则返回Flase
True
>>> s = &#39;ABc&#39;
>>> s.isupper()
False
>>> 

>>> s = &#39;123&#39;
>>> s.isnumeric() #如果字符串只包含数字字符,则返回True,否则返回False
True
>>> s = &#39;123a&#39;
>>> s.isnumeric()
False

>>> &#39;def&#39;.isidentifier() #判断字符串是否包含该语言的保留字
True

>>> &#39;aaa&#39;.isprintable() #判断是否可以打印
True

>>> &#39;&#39;.isspace()
False
>>> &#39; &#39;.isspace() #判断字符串中至少有一个字符且所有都是空格,否则返回false
True
>>> &#39; a&#39;.isspace()
False

>>> &#39;Abc&#39;.istitle() #判断是否是标题 格式,可以理解为首字母大写。
True
>>> &#39;aBC&#39;.istitle()
False

>>> s = &#39;123&#39;
>>> &#39;_&#39;.join(s) #返回一个用指定字符串分隔的字,或者是将指定字符加入到另一个字符中。
&#39;1_2_3&#39;
>>> s.join(&#39;abc&#39;)
&#39;a123b123c&#39;

>>> s = &#39;ABC&#39;
>>> s.lower() #返回的是指定字符串的拷贝,并转化成小写
&#39;abc&#39;

>>> s.ljust(10,&#39;+&#39;) #可以指定宽度,以及填充字符串,返回的是按宽度,填充字符串格式化后的左对齐的字符串。
&#39;ABC+++++++&#39;

>>> &#39;aaabccc&#39;.partition(&#39;b&#39;) #在字符串中查找指定的字符,如找到则返回字符前部分,字符本身和后部分,如没找到则返回字符串和两个空字符串。
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.partition(&#39;e&#39;)
(&#39;aaabccc&#39;, &#39;&#39;, &#39;&#39;)

>>> &#39;aaabccc&#39;.rpartition(&#39;b&#39;) #与partition一样,但是是从右边开始
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.rpartition(&#39;c&#39;)
(&#39;aaabcc&#39;, &#39;c&#39;, &#39;&#39;)


>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;) #用指定字符串替换指定字符串,如果不指定替换次数,则替换所有
&#39;AAAAAbbcc&#39;
>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;,2)
&#39;AAaaabbcc&#39;

>>> &#39;aabbcc&#39;.rfind(&#39;a&#39;) #返回指定子串的最高索引,如果没找到则返回-1,可以指定要开始替换的起始,结束位置。
1
>>> &#39;aabbcc&#39;.rfind(&#39;e&#39;)
-1
>>> &#39;aabbcc&#39;.rindex(&#39;a&#39;) #与上面的rfind一样,只是如果没找到不是返回-1,而是触发错误
1
>>> &#39;aabbcc&#39;.rindex(&#39;e&#39;)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: substring not found

>>> &#39;aa&#39;.rjust(10,&#39;+&#39;) #与ljust()相对应,右对齐
&#39;++++++++aa&#39;
>>> &#39;aa&#39;.ljust(10,&#39;+&#39;)
&#39;aa++++++++&#39;

>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;) ##按指定字符串对目标字符串进行切割,可以指定切割次数
[&#39;aa&#39;, &#39;cc&#39;, &#39;dd&#39;, &#39;ee&#39;]
>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;,2)
[&#39;aa&#39;, &#39;cc&#39;, &#39;ddbee&#39;]

>>> &#39;aabccbddbee&#39;.rsplit(&#39;b&#39;,2) #与split作用相同,但是从右侧开始
[&#39;aabcc&#39;, &#39;dd&#39;, &#39;ee&#39;]

>>> &#39; aabb &#39;.strip() #移除字符串两侧的指定字符串,默认移除空格,需要注意的是可以指定多个字符
&#39;aabb&#39;
>>> &#39; aabb&#39;.strip(&#39;b&#39;)
&#39; aa&#39;
>>> &#39; aabb&#39;.strip(&#39;ab&#39;)
&#39; &#39;
>>> &#39;beaacebb&#39;.rstrip(&#39;eb&#39;) #与strip一样,从右侧删除指定字符,可以为多个
&#39;beaac&#39;

>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines() #按换行符切割显示,如没指定keepends=True则将换行符移除。
[&#39;aa&#39;, &#39;bb&#39;, &#39;cc&#39;, &#39;dd&#39;]
>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines(keepends=True)
[&#39;aa\n&#39;, &#39;bb\n&#39;, &#39;cc\n&#39;, &#39;dd&#39;]

>>> &#39;aabbc&#39;.startswith(&#39;a&#39;) #判断字符串是否以某个字符开头,可以是多字符
True
>>> &#39;aabbc&#39;.startswith(&#39;b&#39;)
False
>>> &#39;aabbc&#39;.startswith(&#39;aab&#39;)
True

>>> &#39;aaBBcc&#39;.swapcase() #转换大小写
&#39;AAbbCC&#39;

>>> &#39;wend is ok&#39;.title() #标题格式,首字母大写,其它字符小写
&#39;Wend Is Ok&#39;

>>> &#39;wend is ok&#39;.upper() #将字符全部转换成大写
&#39;WEND IS OK&#39;

>>> &#39;wend is ok&#39;.zfill(20) #这里的z指zero,用0将字符填充到指定长度
&#39;0000000000wend is ok&#39;
Copy after login

The above is the detailed content of Example explanation of Character string in python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How to train PyTorch model on CentOS How to train PyTorch model on CentOS Apr 14, 2025 pm 03:03 PM

Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to choose the PyTorch version under CentOS How to choose the PyTorch version under CentOS Apr 14, 2025 pm 02:51 PM

When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles