Python Strings

Endswith

>>> "Hello, world!".endswith("!")
True

Join

>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Input

>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'

Get input data from console

Formatting

name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))

#format() Method

txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)

Concatenates

>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'

Check String

>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True

Multiple copies

>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'

String Length

>>> hello = "Hello, World!"
>>> print(len(hello))
13

The len() function returns the length of a string

Looping

>>> for char in "foo":
...     print(char)
f
o
o

Loop through the letters in the word "foo"

Array-like

>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d

Get the character at position 1 or last

Comments