Python Strings

0

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")
print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

a = "Hello"
print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."
""
print(a)


Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Slice From the Start

By leaving out the start index, the range will start at the first character:

b = "Hello, World!"
print(b[:5])

Slice To the End

By leaving out the end index, the range will go to the end:

b = "Hello, World!"
print(b[2:])

Negative Indexing

Use negative indexes to start the slice from the end of the string:

Example

Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

 


Python - Modify Strings

Upper Case

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())


Lower Case

 The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Remove White space

The strip() method removes any white space from the beginning or the end:

 a = " Hello, World! "
print(a.strip()) # returns "Hello, World!" 


String Format

 As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

age = 36
txt = "My name is John, I am " + age
print(txt)

 

Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

 

The format() method takes unlimited number of arguments, and are placed into the respective placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

 

Tags

Post a Comment

0 Comments
Post a Comment (0)
To Top