Close

Python String

[Last Updated: Feb 2, 2022]

In Python strings can be created with single or double quotes or triple single quotes (for multiline string):

scripts/strings.py

greeting = "hello"
greeting2 = 'hi there'
greeting3 = '''hello there!
how are you doing'''

print(greeting)
print(greeting2)
print(greeting3)
# getting type
print(type(greeting))

Output

hello
hi there
hello there!
how are you doing
<class 'str'>

Formatting strings

In Python we can format strings by using format() function

definition of format()

 def format(self, *args, **kwargs): 

Example:

scripts/strings-format-example.py

greeting = "Hi {name}, greeting from {lang}!"
formatted = greeting.format(name="Joe", lang="Python")
print(formatted)

Output

Hi Joe, greeting from Python!

F-strings

F-string does the same thing what str.format() does.
F-strings are string literals that are prefixed by the letter 'f' or 'F'.
This syntax can be desirable if string literals need to support interpolation:

scripts/strings-f-string-example.py

name = "Joe"
lang = "Python"
greeting = F"Hi {name}, greeting from {lang}!"
print(greeting)

Output

Hi Joe, greeting from Python!

Example Project

Dependencies and Technologies Used:

  • Python 3.10.2
Python String Type Select All Download
  • python-string-type
    • scripts
      • strings.py

    See Also