How to convert python str() parameters to string type

 

This article mainly introduces how python str() converts parameters into string types. It has a good reference value and I hope it will be helpful to everyone.

str() converts the parameter to string type

1

2

a = 26

print('我有'+str(a)+'个苹果')

Output: I have 26 apples

Two mechanisms by which Python values ​​are converted to strings

When you first learn Python, you can find that all strings printed through Python are enclosed in quotation marks. But printing through the print statement does not.

reason:

When Python prints a value, it maintains the value's state in the Python code, not the state you want the user to see. Printing through the print statement is the status that the user wants to see.

For example:

1

2

3

4

5

6

7

# 直接打印

>>> "Hello, world!"

'Hello, world!'

# 通过print语句打印

>>> print "Hello, world!"

Hello, world!

But when you want to know the value of a variable, you may be interested in whether it is an integer or a long integer. This can be achieved through two mechanisms in Python that convert values ​​into strings: the str function and the repr function.

str function: It converts the value into a string in a reasonable form so that the user can understand it.

repr function: It creates a string that represents a value in the form of a legal Python expression.

For example:

1

2

3

4

5

6

7

8

9

10

11

# str函数:

>>> print str("Hello, world!")

Hello, world!

>>> print str(10000L)

10000

# repr函数:

>>> print repr("Hello, world!"

'Hello, world!'

>>> print repr(10000L)

10000L

The above is my personal experience. I hope it can give you a reference and help you.

Source: Weidian Reading   https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131781990