Skip to content

String (str)

1. String declaration

There are 3 methods to declare a string:

  • single quotes
  • double quotes
  • triple quotes (for multiple line)

string-declaration.py

py
# single quotes
name = 'John'

# double quotes
name2 = "Ben"

# triple quotes (for multiple line)
name3 = """
Alison
Kai
Tim
Ben
"""

print(name)
print(name2)
print(name3)

print(type(name))
print(type(name2))
print(type(name3))

Results:

John
Ben

Alison
Kai
Tim
Ben

<class 'str'>
<class 'str'>
<class 'str'>

2. Escape quotes (\)

Escape string is use when we need to use multiple same quote in a single line of string

Example we may need escape quotes:

py
# it will get error if repeated quote is use in a single line expression
# greeeting_text = 'Hi, John's Brother'
# ' ' < (Quote of middle will cause conflict)  '

# correct way
greeeting_text = "Hi, John's Brother"
  • using a same quote in a single line of expression will get error.

INFO

  • Solution 1: replace single quote > double quote or vice-versa
  • Solution 2: using Escape quotes (\)
  • By using \ python will treat repeated quote as normal string.

Usage:

py
" \" "

escape-quotes.py

py
name = "\"John\""
print(name)

Results:

"John"

3. String Concatenation (字符串的拼接)

  • using + to join two or more character strings to a new single string

string-concatenation.py

ex: string + string

py
text1 = "Hello "
text2 = "World"

print(text1 + text2)

Results:

Hello World

ex: literal + variable

py
name = "John"
age = 25 # type is int
location = "LA"
print(name + " is " + str(age) + " and live in " + location)

Results:

John is 25 and live in LA

WARNING

int type cannot directly to print, it have to convert to str type.


py
# Wrong
print(name + " is " + age + " and live in " + location)
# Correct
print(name + " is " + str(age) + " and live in " + location)

    print(name + " is " + age + " and live in " + location)
          ~~~~~~~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

4. String Placeholder Concatenation (string interpolation / formatting)

Usage:

string-placeholder.py

1. Single placeholder

py
name = "John"

msg = "My name is %s" % name
print(msg)

Results:

My name is John
  • % means placeholder
  • s means placeholder for string (will convert value to str)
  • %d means placeholder for decimal
  • %f means placeholder for float

2. Multiple placeholder

py
min_salary = 1000
max_salary = 3000

salary_diff = "Salary is between %s and %s" % (min_salary, max_salary)
print(salary_diff)

Results:

Salary is between 1000 and 3000

INFO

  • If multiple placeholder, it requied a bracket, () to receive all of the placeholder value
  • the placeholder value arrangement is same as the position of the placeholder

3. Comprehensive example

py
# %s, %f, %d
current_salary = 5000
salary_grow_rate = 3.5
workers_name = "Ben"

print(
    "%s current salary is %d and he can enjoy a salary grow rate of %f"
    % 
    (workers_name, current_salary, salary_grow_rate)
)

Results:

Ben current salary is 5000 and he can enjoy a salary grow rate of 3.500000

WARNING

The salary_grow_rate here is not precise / accurate, check number precision control.

5. Number precision control

Format:

m.n
  • m control the width of decimal value (int placed value) (ex: %5d to control a decimal value to 5 padding/alignment only, less than that will shows () empty places, if more then the value it remains unchanged)
  • n control the decimal places (ex: %.2f to control a decimal places to 2 places only and round-off at the same time)

Usage:

number-precision-control.py

Control decimal places

py
# %s, %f, %d
current_salary = 5000
salary_grow_rate = 3.55
workers_name = "Ben"

print(
    "%s current salary is %d and he can enjoy a salary grow rate of %.1f"
    % 
    (workers_name, current_salary, salary_grow_rate)
)

Results:

Ben current salary is 5000 and he can enjoy a salary grow rate of 3.5

DANGER

using %.f will cause 3.55 become 4.

6. F-Strings

Format:

f"context {variable_name} context"

Usage:

fstring.py

py
name = "John"
age = 12

print(f"My name is {name} and {age} year old !")

Results:

My name is John and 12 year old !

Conclusion

  • For all of the string joining method, variable can be replace by expression.
  • Only for + joining method has to convert expressions to str type.

Example:

string-conclusion.py

py
name = "John"

print(name + " is the type of " + str(type(name)))
print("%s is the type of %s" % (name, type(name)))
print(f"{name} is the type of {type(name)}")

Results:

John is the type of <class 'str'>
John is the type of <class 'str'>
John is the type of <class 'str'>

Extra