Python Tutorial column introduces 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.'復(fù)制代碼
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."復(fù)制代碼
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())復(fù)制代碼
Save this file as name.py
, and then run it. You will see the following output:
Fulade?Blog復(fù)制代碼
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())復(fù)制代碼
The output is as follows:
FULADE?BLOG fulade?blog復(fù)制代碼
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)復(fù)制代碼
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復(fù)制代碼
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)復(fù)制代碼
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復(fù)制代碼
To add a newline character to a string, use the character combination \n
:
print("Languages:\nPython\nC\nJavaScript")? Languages: Python C JavaScript復(fù)制代碼
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("Languages:\n\tPython\n\tC\n\tJavaScript")?
Languages:
??Python
??C?
??JavaScript復(fù)制代碼</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
, 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?=?"'python?'"favorite_language?=?favorite_language.rstrip()
print(favorite_language)'python'復(fù)制代碼</pre>
<p>為刪除這個(gè)字符串中的空格,你需要將其末尾的空格剔除,再將結(jié)果存回到原來(lái)的變量中。
在我們的日常開(kāi)發(fā)中,經(jīng)常需要修改變量的值,再將新值存回到原來(lái)的變量中。
你還可以剔除字符串開(kāi)頭的空格,或同時(shí)剔除字符串兩端的空格。為此,可分別使用方法 <code>lstrip()
和strip()
:
favorite_language?=?"'?python?'"?print(favorite_language.rstrip())'?python'print(favorite_language.lstrip())'python?'print(favorite_language.strip())'python'復(fù)制代碼
在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)開(kāi)頭和末尾都有空格的字符串。接下來(lái),我們 分別刪除末尾、開(kāi)頭兩端的空格。在實(shí)際程序開(kāi)發(fā)中,這些剔除函數(shù)最常用于在存儲(chǔ)用戶(hù)輸入前對(duì)輸入進(jìn)行清理。
使用字符串時(shí)避免語(yǔ)法錯(cuò)誤
語(yǔ)法錯(cuò)誤是一種經(jīng)常會(huì)出現(xiàn)的錯(cuò)誤。程序中包含非法的Python代碼時(shí),就會(huì)導(dǎo)致語(yǔ)法錯(cuò)誤。 例如,在用單引號(hào)括起的字符串中,如果包含撇號(hào),就將導(dǎo)致錯(cuò)誤。這是因?yàn)檫@會(huì)導(dǎo)致Python將 第一個(gè)單引號(hào)和撇號(hào)之間的內(nèi)容視為一個(gè)字符串,進(jìn)而將余下的文本視為Python代碼,從而引發(fā) 錯(cuò)誤。 下面演示了如何正確地使用單引號(hào)和雙引號(hào)。
message?=?"One?of?Python's?strengths?is?its?perse?community."?print(message)復(fù)制代碼
撇號(hào)位于兩個(gè)雙引號(hào)之間,因此Python解釋器能夠正確地理解這個(gè)字符串:
One?of?Python's?strengths?is?its?perse?community.復(fù)制代碼
然而,如果你使用單引號(hào),Python將無(wú)法正確地確定字符串的結(jié)束位置:
message?=?'One?of?Python's?strengths?is?its?perse?community.' print(message)復(fù)制代碼
而你將看到如下輸出:
message?=?'One?of?Python's?strengths?is?its?perse?community.' SyntaxError:?invalid?syntax復(fù)制代碼
從上面的輸出我們可以看到,錯(cuò)誤發(fā)生在第二個(gè)單引號(hào)后面。這種語(yǔ)法錯(cuò)誤表明,在解釋器看來(lái),其中的有些內(nèi)容不是有效的Python代碼。錯(cuò)誤的來(lái)源多種多樣,這里指出一些常見(jiàn)的。學(xué)習(xí) 編寫(xiě)Python代碼時(shí),你可能會(huì)經(jīng)常遇到語(yǔ)法錯(cuò)誤。
所以,大家在做練習(xí)的時(shí)候也要細(xì)心,避免出現(xiàn)這種小錯(cuò)誤。
相關(guān)免費(fèi)學(xué)習(xí)推薦:python教程(視頻)
The above is the detailed content of Python tutorial strings. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.
