Using Single Quotes:
string1 = 'Hello, World!'
string2 = "Hello, World!"
string3 = '''Hello,
World!'''
string4 = "Hello" + ", " + "World!"
name = "World"
greeting = f"Hello, {name}!"
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."
Dynamic Expression Evaluation: You can include any valid Python expression inside the curly braces.
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}."
pi = 3.14159
text = f"The value of pi is approximately {pi}."
formatted_pi = f"The value of pi to 2 decimal places is {pi:.2f}."
Here's an example showcasing the versatility of f-strings:
name = "Bob"
age = 40
height = 1.8 # in meters
# Using f-string to format the text
text = f"{name} is {age} years old and {height:.2f} meters tall."
print(text)
So, {height:.2f} will format the variable height as a floating-point number with two digits after the decimal point. For example, if height = 1.8, then {height:.2f} would be converted to the string "1.80".
As you can see, f-strings provide a flexible and efficient way to format strings in Python.
str.format() method:
greeting = "Hello, {}!".format(name)
You can access individual characters or slice the string using indices.
first_letter = string1[0] # Output: 'H'
slice1 = string1[0:5] # Output: 'Hello'
# Initialize a string
text = 'Hello, World'
# Use the lower() method to convert all characters to lowercase
lowercase_text = text.lower()
print(f"Lowercase: {lowercase_text}") # Output: 'hello, world'
# Use the upper() method to convert all characters to uppercase
uppercase_text = text.upper()
print(f"Uppercase: {uppercase_text}") # Output: 'HELLO, WORLD'
# Use the replace() method to replace a substring within the string
replaced_text = text.replace('World', 'Everyone')
print(f"Replaced: {replaced_text}") # Output: 'Hello, Everyone'
# Use the split() method to split the string by a specified delimiter
split_text = text.split(', ')
print(f"Splitted: {split_text}") # Output: ['Hello', 'World']
Use a backslash \ to escape characters like quotes within strings.
escaped_string = "He said, \"Hello, World!\""
Use len() function to check the length of a string.
length = len(string1) # Output will be 13 for 'Hello, World!'
0 留言