String in python

String in python

A string is a collection of text. Anything in Python surrounded by ‘’ or “” is called a string.
Single line strings are surrounded by single or double commas while we can write
multiline strings as well using triple commas

x = ‘single line string’
x = “single line string”
y = ”’multiline string
multiline string ”’

Example

name = “Python”

print(name)

message = “I love Python.”

print(message)

Indexing: One way is to treat strings as a list and use index values. For example,

greet = ‘hello’

print(greet[1])       –  e

Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,

greet = ‘hello’

print(greet[-4])           – e

Slicing: Access a range of characters in a string by using the slicing operator colon :  For example

a = “Hello”
print(a[1:5])

String length

a = “Hello, World!”
print(len(a))

IN keyword

………………

txt = “The best things in life are free!”
print(“free” in txt)

………………..

txt = “The best things in life are free!”
if “free” in txt:
print(“Yes, ‘free’ is present.”)

…………

txt = “The best things in life are free!”
print(“expensive” not in txt)

Python String Operations

Comparison

str1 = “Hello, world!”

str2 = “I love Python.”

str3 = “Hello, world!”

print(str1 == str2)

print(str1 == str3)

Join Two or More Strings

greet = “Hello, ”

name = “Ali”

result = greet + name

print(result)

……….

We can iterate through a string using a for loop. For example,

a= ‘Hello’

for letter in a:

print(letter)

Python String Formatting

name = ‘ahmad’

country = ‘UAE’

print(f'{name} is from {country}’)

 

Methods of python string 

Methods             Description

upper()               converts the string to uppercase

lower()                converts the string to lowercase

partition()          returns a tuple

replace()             replaces substring inside

find()                   returns the index of first occurrence of substring

rstrip()                removes trailing characters

split()                  splits string from left

startswith()        checks if string starts with the specified string

isnumeric()         checks numeric characters

index()                 returns index of substring

 

 

Search within CuiTutorial

Scroll to Top