Python 3.6中str()函数作用及str(word.strip(), encoding='utf-8')功能咨询
Hey there! Let's tackle your Python questions clearly and directly:
1. What does the
str() function do in Python 3.6? In Python 3.6 (and all Python 3 versions), the str() function serves two core purposes:
- Convert non-string objects to string type: It turns integers, floats, booleans, or even custom objects into human-readable string representations. For example:
str(42)returns"42"str(3.14)returns"3.14"str(False)returns"False"
- Decode bytes to string (less common): If you pass a bytes object as the first argument, specifying an encoding like
"utf-8"converts those raw bytes into a proper Unicode string. This works exactly like calling.decode(encoding)on the bytes object (e.g.,str(b'hello', 'utf-8')is equivalent tob'hello'.decode('utf-8')).
2. Understanding
str(word.strip(), encoding="utf-8") Let's break this line down piece by piece:
word.strip(): This removes whitespace characters (spaces, tabs, newlines, etc.) from the start and end ofword. For example, ifwordwas" hello! ",word.strip()would output"hello!".str(..., encoding="utf-8"): This syntax is a holdover from Python 2 (wherestrand bytes were interchangeable), which is probably why you struggled to find clear answers online. In Python 3:- If
word.strip()returns a bytes object, this call decodes those bytes into a UTF-8 encoded string. For instance, ifwordwasb' python rocks! ',word.strip()givesb'python rocks!', andstr(..., encoding="utf-8")turns that into the string"python rocks!". - If
word.strip()is already a string (str type), this will throw aTypeError—Python 3'sstr()doesn't accept anencodingargument when the input is a string.
- If
For Python 3, the cleaner, more idiomatic alternatives are:
- If working with bytes: Use
word.strip().decode("utf-8") - If working with strings: Just use
word.strip()(no need for thestr()wrapper at all)
内容的提问来源于stack exchange,提问作者Meraj
相关产品推荐
相关产品推荐

