Home > Backend Development > Python Tutorial > Python tutorial strings

Python tutorial strings

coldplay.xixi
Release: 2020-11-10 17:06:27
forward
2273 people have browsed it

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.'复制代码
Copy after login

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."复制代码
Copy after login

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())复制代码
Copy after login

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

Fulade Blog复制代码
Copy after login

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())复制代码
Copy after login

The output is as follows:

FULADE BLOG
fulade blog复制代码
Copy after login

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)复制代码
Copy after login

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复制代码
Copy after login

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)复制代码
Copy after login

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复制代码
Copy after login

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

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

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()

. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">print(&quot;Languages:\n\tPython\n\tC\n\tJavaScript&quot;)  Languages:   Python   C    JavaScript复制代码</pre><div class="contentsignin">Copy after login</div></div>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:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">favorite_language = &quot;'python '&quot;favorite_language = favorite_language.rstrip() print(favorite_language)'python'复制代码</pre><div class="contentsignin">Copy after login</div></div> <p>为删除这个字符串中的空格,你需要将其末尾的空格剔除,再将结果存回到原来的变量中。 在我们的日常开发中,经常需要修改变量的值,再将新值存回到原来的变量中。 你还可以剔除字符串开头的空格,或同时剔除字符串两端的空格。为此,可分别使用方法 <code>lstrip()strip():

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

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

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

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

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

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

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

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

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

而你将看到如下输出:

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

从上面的输出我们可以看到,错误发生在第二个单引号后面。这种语法错误表明,在解释器看来,其中的有些内容不是有效的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!

Related labels:
source:juejin.im
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template