x010

x010

厚积薄发

String manipulation

Slice Syntax#

sequence[start:stop]
In the following text, t is equivalent to print

a ="12345"
print(a[0])#Output the first one
print(a[-1])#Output the last one
print(a[0:-1])#Output from 0 to the last value (excluding the last value), if you change 0 and -1 to 1 and 5, it will output from the 1st to the 6th
print(a[::-1])#Output in reverse order
print(a[::2])#Output every two, eg: 1 3 5
print(a[6:0:-1])#Output in reverse from the 7th to the 1st, if you change the parameters to 5, the output will be the same, because it outputs from the 6th to the 1st

image.png

String Syntax#

b="   2,  3 ,a  A "
print(b)
print(b.strip())#Remove spaces from both sides
print(b.split(','))#Split characters by comma
print(b.upper())#Convert all lowercase letters to uppercase
print(b.lower())#Convert to lowercase
print(b.replace(",","!"))#Replace commas with exclamation marks

image.png

Formatted Output#

a=input("Hello, please enter your name:")
b=int(input("Please enter your age:"))#Need to convert the input to int type
print("Hello, my name is %s, I am %d years old"%(a,b))

The input() function returns a string (str) type, and when printing the age, you used the %d format specifier, which is for integers. If the input age is not purely numeric, or if you want to ensure the code is more robust, it's best to convert the input age string to an integer.

a=input("Hello, please enter your name:")
b=int(input("Please enter your age:"))
print("Hello, my name is {i_a}, I am {i_b} years old".format(i_a=a,i_b=b))#Note the curly braces, achieved through the .format() function
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.