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

Python Strings

The document provides an overview of strings in Python, explaining their definition, creation using single or double quotes, and various operations such as indexing, slicing, and concatenation. It highlights the immutability of strings, the ability to create multiline strings, and introduces several string methods for manipulation and testing. Additionally, it covers string length, membership testing, and iterating through strings.

Uploaded by

lokesh pappala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Strings

The document provides an overview of strings in Python, explaining their definition, creation using single or double quotes, and various operations such as indexing, slicing, and concatenation. It highlights the immutability of strings, the ability to create multiline strings, and introduces several string methods for manipulation and testing. Additionally, it covers string length, membership testing, and iterating through strings.

Uploaded by

lokesh pappala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

In computer programming, a string is a

sequence of characters. For


example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l',
and 'o'.
We use single quotes or double quotes to
represent a string in Python. For example,

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'
Here, we have created a string variable
named string1. The variable is initialized with
the string Python Programming.

Example: Python String


# create string type variables

name = "Python"
print(name)
message = "I love Python."
print(message)
Output
Python
I love Python.
In the above example, we have created string-
type variables: name and message with
values "Python" and "I love
Python" respectively.
Here, we have used double quotes to represent
strings but we can use single quotes too.

Access String Characters in Python


We can access the characters in a string in
three ways.
 Indexing: One way is to treat strings as
a list and use index values. For example,
greet = 'hello'

# access 1st index element


print(greet[1]) # "e"
 Negative Indexing: Similar to a list, Python
allows negative indexing for its strings. For
example,
greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"
 Slicing: Access a range of characters in a

string by using the slicing operator colon :.


For example,
greet = 'Hello'

# access character from 1st index to 3rd


index
print(greet[1:4]) # "ell"
Note: If we try to access an index out of the
range or use numbers other than an integer, we
will get errors.

Python Strings are immutable


In Python, strings are immutable. That means
the characters of a string cannot be changed.
For example,
message = 'Hola Amigos'
message[0] = 'H'
print(message)
Output
TypeError: 'str' object does not support
item assignment
However, we can assign the variable name to a
new string. For example,
message = 'Hola Amigos'

# assign new string to message variable


message = 'Hello Friends'

prints(message); # prints "Hello Friends"

Python Multiline String


We can also create a multiline string in Python.
For this, we use triple double quotes """ or triple
single quotes '''. For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)
Output
Never gonna give you up
Never gonna let you down
In the above example, anything inside the
enclosing triple-quotes is one multiline string.

Python String Operations


There are many operations that can be
performed with strings which makes it one of
the most used data types in Python.
1. Compare Two Strings
We use the == operator to compare two strings.
If two strings are equal, the operator
returns True. Otherwise, it returns False. For
example,
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Output
False
True
In the above example,
 str1 and str2 are not equal. Hence, the
result is False.
 str1 and str3 are equal. Hence, the result
is True.
2. Join Two or More Strings
In Python, we can join (concatenate) two or
more strings using the + operator.
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


In the above example, we have used
the + operator to join two
strings: greet and name.

Iterate Through a Python String


We can iterate through a string using a for loop.
For example,
greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)
Output
H
e
l
l
o

Python String Length


In Python, we use the len() method to find the
length of a string. For example,
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5

String Membership Test


We can test if a substring exists within a string
or not, using the keyword in.
print('a'in'program') # True
print('at'notin'battle') False

Methods of Python String


Besides those mentioned above, there are
various string methods present in Python. Here
are some of those methods:
Methods Description
upper() converts the string to uppercase
converts the string to lowercase
# example string
lower() string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())

replace() replaces substring inside


text = 'bat ball'

# replace 'ba' with 'ro'


replaced_text = text.replace('ba',
'ro')

print(replaced_text)

# Output: rot roll

returns the index of first occurrence of


substring
message = 'Python is a fun
programming language'

find() # check the index of 'fun'


print(message.find('fun'))

# Output: 12

removes trailing characters


title = 'Python Programming '

# remove trailing whitespace from


rstrip() title
result = title.rstrip()
print(result)
splits string from left
text = 'Python is a fun programming
language'

# split the text from space


split() print(text.split(' '))

# Output: ['Python', 'is', 'a',


'fun', 'programming', 'language']

checks if string starts with the specified


string
message = 'Python is fun'

# check if the message starts with


startswith() Python
print(message.startswith('Python'))

# Output: True

isnumeric() checks numeric characters


pin = "523"
# checks if every character of pin
is numeric
print(pin.isnumeric())

# Output: True

returns index of substring


text = 'Python is fun'

# find the index of is


result = text.index('is')
index()
print(result)

# Output: 7

You might also like