search

Python tutorial strings

Nov 10, 2020 pm 05:06 PM
pythonstring

Python Tutorial column introduces strings.

Python tutorial strings

A string or string (String) is a string of characters composed of numbers, letters, and underscores.

String

A string is a series of characters. In Python, everything enclosed in quotation marks is a string, and the quotation marks can be single quotation marks or double quotation marks, as shown below:

"This is a string."   'This is also a string.'复制代码

This flexibility allows you to Contains quotation marks and apostrophes:

'I told my friend, "Python is my favorite language!"'"The language 'Python' is named after Monty Python, not the snake." "One of Python's strengths is its perse and supportive community."复制代码

Article starting address

Use method to modify the case of string

For strings, the most executable One of the simple things to do is to change the case of the words in it. Please look at the following code and try to judge its effect:

name = "fulade blog" print(name.title())复制代码

Save this file as name.py, and then run it. You will see the following output:

Fulade Blog复制代码

In this example, the lowercase string "fulade blog" is stored in the variable name. In the print() statement, the method title() appears after this variable. In name.title(), the period (.) after name allows Python to perform the operation of method title() on the variable name. Each method is followed by a pair of parentheses because methods usually require some parameters to do their work. These parameters are often written in parentheses. The method title() does not require parameters, so the brackets after it are empty. The implementation result of title() is to display each word with the first letter capitalized, that is, change the first letter of each word to capitalized. There are several other useful ways to handle case. For example, to change a string to all uppercase or all lowercase, you can do as follows:

name = "Fulade Blog"  print(name.upper()) 
print(name.lower())复制代码

The output is as follows:

FULADE BLOG
fulade blog复制代码

Splicing string

In many cases, we need to merge strings. For example, you might want to store the first and last name in separate variables and then combine them into one when you want to display the name:

first_name = "Fu"last_name = "lade"full_name = first_name + " " + last_name
print(full_name)复制代码

Python uses the plus sign ( ) to combine strings. In this example, we use to combine first_name, spaces and last_name, to get the complete name, the result is as follows:

Fu lade复制代码

This method of merging strings is called splicing. Concatenation allows you to create a complete string from the strings stored in variables. Let's look at another example:

first_name = "fu"last_name = "lade"full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"print(message)复制代码

The above code displays the message "Hello, Fu Lade!", but stores this message in a variable, which makes the final print statement Much simpler.

Use tab characters (pressing the Tab key to generate spaces is called tab characters) or newline characters to add whitespace

In programming, whitespace generally refers to any non-printing characters such as spaces, tabs, and newlines. You can use whitespace to organize output and make it more readable. To add a tab character to a string, use the character combination \t, as shown in the following code:

print("Python")
Python
print("\tPython")
    Python复制代码

To add a newline character to a string, use the character combination \n:

print("Languages:\nPython\nC\nJavaScript") 
Languages:
Python
C
JavaScript复制代码

It is also possible to include both tab and newline characters in the same string. The string "\n\t" tells Python to wrap to the next line and Add a tab character to the beginning of the next line. The following example demonstrates how to use a single-line string to generate four lines of output: confuse. To a programmer,

'python'

and 'python ' look almost the same, but to a compiler, they are two different strings. Python is able to detect extra whitespace in 'python' and assume it is meaningful - unless you tell it otherwise. Whitespace is important because you often need to compare two strings to see if they are identical. For example, when a user logs in to the website, we need to compare the username. But in some scenarios we don't want spaces. Therefore, Python provides a very simple method to remove spaces. Python can find extra whitespace at the beginning and end of strings. To ensure that there are no whitespaces at the end of the string, use the method

rstrip()

. <pre class="brush:php;toolbar:false">print(&quot;Languages:\n\tPython\n\tC\n\tJavaScript&quot;)  Languages:   Python   C    JavaScript复制代码</pre>The string stored in variable favorite_language contains extra spaces at the end. When you run this code, you can see the space at the end. After calling the method rstrip() on the variable

favorite_language

, this extra space is deleted. However, this deletion is only temporary. When you output the value of favorite_language again, you will find that the string is the same as when you entered it, still containing extra spaces. To permanently remove spaces from this string, the result of the removal operation must be saved back to a variable:<pre class="brush:php;toolbar:false">favorite_language = &quot;'python '&quot;favorite_language = favorite_language.rstrip() print(favorite_language)'python'复制代码</pre> <p>为删除这个字符串中的空格,你需要将其末尾的空格剔除,再将结果存回到原来的变量中。 在我们的日常开发中,经常需要修改变量的值,再将新值存回到原来的变量中。 你还可以剔除字符串开头的空格,或同时剔除字符串两端的空格。为此,可分别使用方法 <code>lstrip()strip():

favorite_language = "' python '" print(favorite_language.rstrip())' python'print(favorite_language.lstrip())'python 'print(favorite_language.strip())'python'复制代码

在这个示例中,我们首先创建了一个开头和末尾都有空格的字符串。接下来,我们 分别删除末尾、开头两端的空格。在实际程序开发中,这些剔除函数最常用于在存储用户输入前对输入进行清理。

使用字符串时避免语法错误

语法错误是一种经常会出现的错误。程序中包含非法的Python代码时,就会导致语法错误。 例如,在用单引号括起的字符串中,如果包含撇号,就将导致错误。这是因为这会导致Python将 第一个单引号和撇号之间的内容视为一个字符串,进而将余下的文本视为Python代码,从而引发 错误。 下面演示了如何正确地使用单引号和双引号。

message = "One of Python's strengths is its perse community." print(message)复制代码

撇号位于两个双引号之间,因此Python解释器能够正确地理解这个字符串:

One of Python's strengths is its perse community.复制代码

然而,如果你使用单引号,Python将无法正确地确定字符串的结束位置:

message = 'One of Python's strengths is its perse community.'
print(message)复制代码

而你将看到如下输出:

message = 'One of Python's strengths is its perse community.'
SyntaxError: invalid syntax复制代码

从上面的输出我们可以看到,错误发生在第二个单引号后面。这种语法错误表明,在解释器看来,其中的有些内容不是有效的Python代码。错误的来源多种多样,这里指出一些常见的。学习 编写Python代码时,你可能会经常遇到语法错误。

所以,大家在做练习的时候也要细心,避免出现这种小错误。

相关免费学习推荐:python教程(视频)

The above is the detailed content of Python tutorial strings. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

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.

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft