【Python】String (2)

【Python】String (2)

 Using Single Quotes:


string1 = 'Hello, World!'

Using Double Quotes:

string2 = "Hello, World!"
Using Triple Quotes for Multi-line Strings:

string3 = '''Hello,
World!'''

You can concatenate (join) two or more strings using the + operator.

string4 = "Hello" + ", " + "World!"

f-strings (Python 3.6+):

name = "World"
greeting = f"Hello, {name}!"

Introduced in Python 3.6, f-strings (formatted string literals) offer a concise and convenient way to embed expressions and variables inside string literals. To create an f-string, you prefix the string with the letter "f" or "F" before the opening quotation mark. You can then include expressions or variables inside curly braces ({}) directly within the string.

name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."

Readability: f-strings are generally easier to read and write compared to other string formatting methods like % formatting or the str.format() method.

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}."

String Conversion: f-strings automatically convert non-string types to strings, so there's no need to explicitly call the str() function.

pi = 3.14159
text = f"The value of pi is approximately {pi}."

Precision and Formatting: You can specify the formatting for floating-point numbers, alignment, and other formatting options.

formatted_pi = f"The value of pi to 2 decimal places is {pi:.2f}."

Speed: f-strings are generally faster than the older % formatting or str.format() because they are evaluated at runtime.
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)


In the f-string expression text = f"{name} is {age} years old and {height:.2f} meters tall.", the .2f is a format specifier used to control the way the floating-point number is displayed.

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'

Strings come with built-in methods like lower(), upper(), replace(), split(), etc.

# 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 留言