0% found this document useful (0 votes)
5 views

02-Strings

Uploaded by

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

02-Strings

Uploaded by

Rajesh Prasad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

qep1jxkur

October 23, 2024

___
Content Copyright by Pierian Data

1 Strings
Strings are used in Python to record text information, such as names. Strings in Python are actually
a sequence, which basically means Python keeps track of every element in the string as a sequence.
For example, Python understands the string ”hello’ to be a sequence of letters in a specific order.
This means we will be able to use indexing to grab particular letters (like the first letter, or the
last letter).
This idea of a sequence is an important one in Python and we will touch upon it later on in the
future.
In this lecture we’ll learn about the following:
1.) Creating Strings
2.) Printing Strings
3.) String Indexing and Slicing
4.) String Properties
5.) String Methods
6.) Print Formatting

1.1 Creating a String


To create a string in Python you need to use either single quotes or double quotes. For example:
[2]: # Single word
'hello'

[2]: 'hello'

[3]: # Entire phrase


'This is also a string'

[3]: 'This is also a string'

1
[4]: # We can also use double quote
"String built with double quotes"

[4]: 'String built with double quotes'

[5]: # Be careful with quotes!


' I'm using single quotes, but this will create an error'

Cell In[5], line 2


' I'm using single quotes, but this will create an error'
^
SyntaxError: unterminated string literal (detected at line 2)

The reason for the error above is because the single quote in I’m stopped the string. You can use
combinations of double and single quotes to get the complete statement.
[6]: "Now I'm ready to use the single quotes inside a string!"

[6]: "Now I'm ready to use the single quotes inside a string!"

Now let’s learn about printing strings!

1.2 Printing a String


Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct
way to display strings in your output is by using a print function.
[8]: # We can simply declare a string
'Hello World'

[8]: 'Hello World'

[9]: # Note that we can't output multiple strings this way


'Hello World 1'
'Hello World 2'

[9]: 'Hello World 2'

We can use a print statement to print a string.


[10]: print('Hello World 1')
print('Hello World 2')
print('Use \n to print a new line')
print('\n')
print('See what I mean?')

2
Hello World 1
Hello World 2
Use
to print a new line

See what I mean?

1.3 String Basics


We can also use a function called len() to check the length of a string!

[11]: len('Hello World')

[11]: 11

Python’s built-in len() function counts all of the characters in the string, including spaces and
punctuation.

1.4 String Indexing


We know strings are a sequence, which means Python can use indexes to call parts of the sequence.
Let’s learn how this works.
In Python, we use brackets [] after an object to call its index. We should also note that indexing
starts at 0 for Python. Let’s create a new object called s and then walk through a few examples of
indexing.
[12]: # Assign s as a string
s = 'Hello World'

[13]: #Check
s

[13]: 'Hello World'

[14]: # Print the object


print(s)

Hello World
Let’s start indexing!
[15]: # Show first element (in this case a letter)
s[0]

[15]: 'H'

[16]: s[1]

3
[16]: 'e'

[17]: s[2]

[17]: 'l'

We can use a : to perform slicing which grabs everything up to a designated point. For example:
[18]: # Grab everything past the first term all the way to the length of s which is␣
↪len(s)

s[1:]

[18]: 'ello World'

[19]: # Note that there is no change to the original s


s

[19]: 'Hello World'

[20]: # Grab everything UP TO the 3rd index


s[:3]

[20]: 'Hel'

Note the above slicing. Here we’re telling Python to grab everything from 0 up to 3. It doesn’t
include the 3rd index. You’ll notice this a lot in Python, where statements and are usually in the
context of “up to, but not including”.
[21]: #Everything
s[:]

[21]: 'Hello World'

We can also use negative indexing to go backwards.


[22]: # Last letter (one index behind 0 so it loops back around)
s[-1]

[22]: 'd'

[23]: # Grab everything but the last letter


s[:-1]

[23]: 'Hello Worl'

We can also use index and slice notation to grab elements of a sequence by a specified step size
(the default is 1). For instance we can use two colons in a row and then a number specifying the
frequency to grab elements. For example:

4
[24]: # Grab everything, but go in steps size of 1
s[::1]

[24]: 'Hello World'

[25]: # Grab everything, but go in step sizes of 2


s[::2]

[25]: 'HloWrd'

[26]: # We can use this to print a string backwards


s[::-1]

[26]: 'dlroW olleH'

1.5 String Properties


It’s important to note that strings have an important property known as immutability. This means
that once a string is created, the elements within it can not be changed or replaced. For example:
[27]: s

[27]: 'Hello World'

[29]: # Let's try to change the first letter to 'x'


s[0] = 'x'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[29], line 2
1 # Let's try to change the first letter to 'x'
----> 2 s[0] = 'x'

TypeError: 'str' object does not support item assignment

Notice how the error tells us directly what we can’t do, change the item assignment!
Something we can do is concatenate strings!
[30]: s

[30]: 'Hello World'

[31]: # Concatenate strings!


s + ' concatenate me!'

[31]: 'Hello World concatenate me!'

5
[32]: # We can reassign s completely though!
s = s + ' concatenate me!'

[33]: print(s)

Hello World concatenate me!

[34]: s

[34]: 'Hello World concatenate me!'

We can use the multiplication symbol to create repetition!


[35]: letter = 'z'

[36]: letter*10

[36]: 'zzzzzzzzzz'

1.6 Basic Built-in String methods


Objects in Python usually have built-in methods. These methods are functions inside the object
(we will learn about these in much more depth later) that can perform actions or commands on
the object itself.
We call methods with a period and then the method name. Methods are in the form:
object.method(parameters)
Where parameters are extra arguments we can pass into the method. Don’t worry if the details
don’t make 100% sense right now. Later on we will be creating our own objects and functions!
Here are some examples of built-in methods in strings:
[37]: s

[37]: 'Hello World concatenate me!'

[38]: # Upper Case a string


s.upper()

[38]: 'HELLO WORLD CONCATENATE ME!'

[39]: # Lower case


s.lower()

[39]: 'hello world concatenate me!'

[40]: # Split a string by blank space (this is the default)


s.split()

6
[40]: ['Hello', 'World', 'concatenate', 'me!']

[41]: # Split by a specific element (doesn't include the element that was split on)
s.split('W')

[41]: ['Hello ', 'orld concatenate me!']

There are many more methods than the ones covered here. Visit the Advanced String section to
find out more!

1.7 Print Formatting


We can use the .format() method to add formatted objects to printed string statements.
The easiest way to show this is through an example:
[42]: 'Insert another string with curly brackets: {}'.format('The inserted string')

[42]: 'Insert another string with curly brackets: The inserted string'

[4]: # List to string


string = "abracadabra"
l = list(string)
l[5] = 'k'
string = ''.join(l)
print(string)

abrackdabra
Sample Input
ABCDCDC CDC
Sample Output
2
[5]: def count_substring(string, sub_string):
count = 0
l = list(string)
for i in range(0, len(l)):
st = ""
for j in range(0, len(sub_string)):
k = (i+j)
if k < len(l):
st += l[k]
if st == sub_string:
count += 1
return count

if __name__ == '__main__':

7
string = input().strip()
sub_string = input().strip()

count = count_substring(string, sub_string)


print(count)

2
ABCDEFGHIJKLIMNOQRSTUVWXYZ 4
ABCD EFGH IJKL IMNO QRST UVWX YZ
[ ]: import textwrap

def wrap(string, max_width):


st = ""
j = 0
l = list(string)
ll = []
max_width1 = max_width
while max_width < len(string):
for i in range(j, max_width):
st += l[i]
j += max_width1
max_width += max_width1
ll.append(st)
st = ""
else:
f = len(string)
d = f%max_width1
ll.append(string[-d:])

er = ""
for i in ll:
er += i + "\n"
return er

if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)

We will revisit this string formatting topic in later sections when we are building our projects!

1.8 Next up: Lists!

You might also like