../_images/search-banner22.png

Strings

Snippets on strings manipulation.

Define long string (use brackets to join multiline string)

string = ("this is a "
          "really long long "
          "string")
print(string)

# Output
this is a really long long string

Define long string (use backslash to join multiline string)

string = "this is a " \
         "really long long " \
         "string"
print(string)

# Output
this is a really long long string

Define long string (use triple quotes to join a multiline string)

string = """This is a multi line
string that keeps the newline."""
print(string)

# Output
This is a multi line
string that keeps the newline.

Pad a string with leading 0s

# add leading 0s to string 50 until entire string is 10 chars
txt = "50"
x = txt.zfill(10)
print(x)

# Output
0000000050

Reverse a string

'hello world'[::-1]

# Output
dlrow olleh

Check if string is number

# returns True if all the characters are digits,
# otherwise False

a = "123"
a.isdigit()

# Output
True

b = "123abc"
b.isdigit()

# Output
False

Combining strings (concatenation)

first = 'Albert'
last = 'Einstein'
full = first + ' ' + last
print(full)

# Output
Albert Einstein