I don't understand how to wrap the str integer value.

Asked 1 years ago, Updated 1 years ago, 312 views

print(str(len(hope))) #Counting the number of characters
print(len(hope))

Both sentences above work well.

print("created password:" + cut1[:3] + str(len(cut1)) + str(cut1.count("e") + "!") #cut1 is a string(?) variable

Why does this sentence need a str to work?

Do I have to wrap the integer variable with str?

python

2022-10-06 01:00

2 Answers

Because of the + operation.

a = "123" + 123
a = 123 + "123"

The above two operations cause different errors. Because strings and numbers can't be added together. String addition serves to combine the two strings as you used them.
If you want to create a string that connects characters in the print function, you must make all str to perform a plus operation. Or you can use the f-string.

print(f"created password: {cut1[:3]}{len(cut1)}{cut1.count("e")}!")

When using f-string, it does not cause problems because it is not a string plus operation.(Of course, it is used internally)


2022-10-06 01:00

Different types cannot be added.

len() => int
'e' => str
a = 'qeasdf;llaj'
b = len(a)
print(type(a))
print(type(b))


2022-10-06 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.