Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Strings in Python

د.وثيق

Uploaded by

wthyq3023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Strings in Python

د.وثيق

Uploaded by

wthyq3023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

"!

txt = "The best things in life are free


print("free" in txt)

print(len(txt))

"!txt = "The best things in life are free


:if "free" in txt
print("Yes, 'free' is present.")

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

"!b = "Hello, World


print(b[2:5])

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

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

Get the characters from position 2, and all the way 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])

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


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

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

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

Remove Whitespace
Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.

Example
The strip() method removes any whitespace from the beginning or the
end:

a = " Hello, World! "


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

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

The split() method returns a list where the text between the
specified separator becomes the list items.

The split() method splits the string into substrings if it finds


instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

You might also like