1. Naming rules for variables
- Variable names can contain only letters, numbers, and underscores. Variable names can begin with a letter or underscore, but cannot begin with a number, for example, you can name a variable message_1, but you cannot name it 1_message.
- Variable names cannot contain spaces, but you can use underscores to separate words in them. For example, the variable name greeting_message possible, but the variable name greeting message throws an error.
- Do not use Python keywords and function names as variable names, that is, do not reserve words for special purposes using Python, such as print (see Appendix A.4).
- Variable names should be both brief and descriptive. For example, name is better than N, Student_name is better than S_n, Name_length is better than length_of_persons_name.
- Use the lowercase l and the capital Letter o sparingly, as they may be mistaken for numbers 1 and 0.
2, String: is a series of characters. In Python, a string is enclosed in quotation marks, where the quotation marks can be single quotes or double quotes.
' Hello python world! ' " The language ' Python ' is named after Monty Python and not the snake. "
3. Use the method to modify the casing of the string.
- Title () displays each word in uppercase, with the first letter of each word capitalized.
- Upper () change each word to uppercase.
- Lower () Each word is changed to lowercase.
name = ' Tom Frank ' Print (Name.title ())
Print (Name.upper ())
Print (Name.lower ()) Output results: Tom Frank
TOM FRANK
Tom Frank
4. Merging stitching strings
first_name = ' Tom ' Last_naem = ' Frank ' full_name = first_name + ' + last_nameprint (full_name) print ("Hello," + full_name.t Itle () + "!")
5. Add blanks with tabs or line breaks
- Use the character combination \ t to add tabs
- Use character combination \ n, line break
Print ("Languages:\n\tpython\n\tc\n\tjava") output result: Languages: Python C Java
6. Delete Blank
- Use Rstrip () to remove the trailing blanks
favorite_languages = ' Python '
#输出原值
Print (favprite_langes)
#去掉末尾空白, Temporary
Print (Favorit_languages.rstrip ())
#永久去掉末尾空白
Favorite_languages = Favorite_languages.rstrip ()
Print (favorite_languages)
- Use Lstrip () to remove the beginning blank
favorite_languages = ' Python ' #输出原值print (favorite_languages) #去掉开头空白, temporary print (Favorite_languages.lstrip ()) # Permanently remove the opening blank favorite_languages = Favorite_languages.lstrip () print (favorite_languages)
- Use strip () to remove both ends of the blank
favoriet_languages = ' Pyrhon ' #输出原值print (favorite_languages) #去掉两端空白print (Favorite_languages.strip ())
7. Use the function str () to avoid type errors
Age = 24message = "Happy" + str (age) + "rd birthday!" Print (message)
Python basic syntax