Python from rookie to expert (7): string

Source: Internet
Author: User
Tags stdin

1. Single-quote strings and escape characters

strings, like numbers, are values that can be used directly, entering strings directly in the Python console, such as "Hello World," and outputting the string as is, except in single quotes.

>>> "Hello World"‘Hello World‘

So what's the difference between a string enclosed in double and single quotes? In fact, there is no difference. It's just convenient when you're outputting single or double quotes. For example, entering ' let's go! ' in the Python console throws the following error.

>>> ‘Let‘s go!‘  File "<stdin>", line 1    ‘Let‘s go!‘         ^SyntaxError: invalid syntax

This is because the Python interpreter cannot tell if the single quotation mark in the middle of the string is a normal character or an extra single quotation mark, so it throws a syntax error exception. There are many ways to output single quotes, one of which is to enclose the string in double quotation marks.

>>> "Let‘s go!""Let‘s go!"

Now the output single quotation mark is solved, but how to output double quotation marks? It's really simple, just enclose the string in single quotes.

>>> ‘我们应该在文本框中输入"Python"‘‘我们应该在文本框中输入"Python"‘

Now that both the output single quote and the output double quotation mark are resolved, how do you output both single and double quotes? For this requirement, use another knowledge point introduced in this sectionto: Escape character. The escape character in the Python language is a backslash (\). The escape character's function is to tell the Python interpreter that the backslash is followed by a part of the string, rather than the single or double quotation marks used to enclose the string. So if the string contains both single and double quotes, then the escape character is required.

print(‘Let\‘s go!. \"一起走天涯\"‘)          #  Let‘s go!. "一起走天涯"

In this line of code, both single and double quotes are escaped characters, in this case, because the string is enclosed in single quotes, it is not necessary to use the escape character for double quotes if it contains double quotes.
The following example shows the use of single and double quotes in the Python language, and the use of escape characters in strings.

实例位置:PythonSamples\src\chapter2\demo2.10.py# 使用单引号的字符串,输出结果:Hello Worldprint(‘Hello World‘)        # 使用双引号的字符串,输出结果:Hello Worldprint("Hello World")#  字符串中包含单引号,输出结果:Let‘s go!print("Let‘s go!")#  字符串中包含双引号,输出结果:"一起走天涯"print(‘"一起走天涯"‘)#  字符串中同时包含单引号和双引号,其中单引号使用了转义符,输出结果:Let‘s go! "一人我饮酒醉"print(‘Let\‘s go! "一人我饮酒醉" ‘)

The program runs as shown in the results.

2. Stitching strings

When you output a string, sometimes the string is very long, in which case the string can be written in multiple parts and then stitched together. We can try one of the following notation.

>>> ‘Hello‘ ‘world‘‘Helloworld‘

The notation is to write two strings together, with 0 to n spaces in the middle of a string. Now let's see if we can combine the values of the two string variables in this way.

>>> x = ‘hello‘>>> y = ‘world‘>>> x y  File "<stdin>", line 1    x y      ^SyntaxError: invalid syntax

As we can see, if a variable of two string types is written next to each other, the Python interpreter will think of it as a syntax error, so this is not actually a concatenation of strings, it's just a way of writing it, and it must be two or more string values written together, and no variables can occur. Otherwise, the Python interpreter will consider it a syntax error.

If you want to concatenate strings, use the plus sign (+), which is the addition of the string.

>>> x = ‘Hello ‘>>> x + ‘World‘‘Hello World‘

The following code demonstrates the method of string concatenation.

# 将字符串写到一起输出,运行结果:helloworld世界你好print("hello"   "world"  "世界你好")        x = "hello"     #  声明字符串变量xy = "world"     #  声明字符串变量y #print(x y)         # 抛出异常,变量不能直接写到一起print(x + y)        # 字符串拼接,要使用加号(+),运行结果:helloworld

The program runs as shown in the results.

"Python from rookie to master" began to reprint, please pay attention to

3. Preserve the authenticity of strings

In the previous article on the application of the escape character (\), in fact, the escape character can not only output single and double quotes, but also control the format of the string, for example, using "\ n" for line wrapping, if the string contains "\ n", then "\ n" after all the characters will be moved to the next line.

>>> print(‘Hello\nWorld‘)HelloWorld

If you want to mix output numbers and strings, and wrap them, you can first convert the numbers to strings using the STR function, and then add "\ n" where you want the line to wrap.

>>> print(str(1234) + "\n" + str(4321))12344321

Sometimes, however, we do not want the Python parser to escape the special characters and want to output as the original string, which requires the use of the REPR function.

>>> print(repr("Hello\nWorld"))‘Hello\nWorld‘

Strings that are output using the REPR function are enclosed in a pair of single quotes.
In fact, if you only want to output "\ n" or other similar escape characters, you can also use two backslashes to output "\", so that "\" after the n will be considered ordinary characters.

>>> print("Hello\\nWorld")Hello\nWorld

In addition to the repr and escape characters described earlier, adding "R" in front of a string can also output a string as is.

>>> print(r"Hello\nWorld")Hello\nWorld

Now, to summarize, if a string is output (not escaped) by the original content, there are 3 ways to do so.

? repr function

? Escape character (\)

? Add "R" to the front of the string

The following example demonstrates the use of the STR and REPR functions.

# 输出带“\n"的字符串,运行结果:

The program runs as shown in the results.

As we can see, the "

4. Long string

In the previous article on the application of the escape character (\), in fact, the escape character can not only output single and double quotes, but also control the format of the string, for example, using "\ n" for line wrapping, if the string contains "\ n", then "\ n" after all the characters will be moved to the next line.

In the previous article, text that uses 3 single or double quotation marks becomes a multiline comment, in fact, if you use the print function to output such a string, or assign it to a variable, it becomes a long string. The original format is preserved in long strings.

print("""Hello          # 长字符串,会按原始格式输出         

If you use a long string to represent a string, you can mix double and single quotes in the middle without having to add the escape character.

print("""Hell"o"            #  长字符串,中间混合使用双引号和单引号         W‘o‘rld"""

For ordinary strings, you can also use multiple lines to represent them. You only need to add the escape character (\) after each line, so that the line break itself is "escaped" and is automatically ignored, so it will eventually become a line of strings.

print("Hello\n          # 输出一行字符串     World")

The following example shows the use of a long string.

print(‘‘‘I                      # 使用3个单引号定义长字符串       ‘love‘          "Python"          ‘‘‘    )s = """Hello                    #  使用双引号定义长字符串    World       世界    你好"""print(s)                        #  输出长字符串print("Hello\                   #  每行字符串在回车符之前用转义符,就可以将字符串写成多行   World")

The program runs as shown in the results.

"Python from rookie to Master" has been published, began to serial, buy send video lessons

Python from rookie to expert (7): string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.