Python Study Notes-string, Sequences

Source: Internet
Author: User

I. Differences between input () and raw_input ()

 

Code

  1 >>> buck = input("Enter your name: ")
2 Enter your name: liu
3
4 Traceback (most recent call last):
5 File "<pyshell#1>", line 1, in <module>
6 buck = input("Enter your name: ")
7 File "<string>", line 1, in <module>
8 NameError: name 'liu' is not defined
9  >>> buck = raw_input('Enter your name: ')
10 Enter your name: liu

 

As shown in the preceding example, raw_input () regards the input as a string, while input is not. Input () judges the type based on the input, of course, if you want to enter a string, you must quote it with money.

Ii. Output Problems

If we define an integer and output it with the string at the same time, as shown below:

 

Code

 >>> n = 20
>>> print('the num is '+20)

Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
print('the num is '+20)
TypeError: cannot concatenate 'str' and 'int' objects

 

As you can see, the plus sign cannot be used directly. There are three solutions:

First, you can convert n to a string using the STR () built-in function:

 

 >>> n = str(n)
>>> print('the num is '+ n)
the num is 20

 

The second type is the plus sign. The key is under the ESC key, for example:

 

 >>> b = 20
>>> print('the num is '+ `b`)
the num is 20

 

The third is to use placeholders, which are similar to the placeholders in C language, but note that the % instead of comma is used to connect strings with other types of data.

 

 >>> print('the num is %d ' % b)
the num is 20

 

Iii. Sequences. This is a bit like an array. below is its definition and truncation (slicing)

 

Code

 >>> example = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> example[:8]
[0, 1, 2, 3, 4, 5, 6, 7]
>>> example[-5:]
[5, 6, 7, 8, 9]
>>> example[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> example[1:8:2]
[1, 3, 5, 7]
>>> example[::-2]
[9, 7, 5, 3, 1]

 

 

 

 

 

 

 

 

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.