0% found this document useful (0 votes)
78 views10 pages

Python String Basics and Functions

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

Python String Basics and Functions

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python string

A string is a series of characters. In Python, anything inside quotes is a string.


And you can use either single or double quotes.

Example 1:

str1="This is a String"

str2='''This is a String'''

str3='This is a String'

print(str1)

print(str2)

print(str3)

Output:

This is a String

This is a String

This is a String

Example 2:

str1="This is a "important" String"

print(str1)

Output:

Error

Example 3:

str1='This is a "important" String'

print(str1)

Output:

This is a "important" String

Example 4:
str1='This is Kapil's notebook'

print(str1)

Output:

Error

Example 5:

str1="This is Kapil's notebook"

print(str1)

Output:

This is Kapil's notebook

Example 6:

print('''this is

a string

in seperate

lines''')

Output:

this is

a string

in seperate

lines

Example 7:

str='it's a wonderful topic'

print(str)

Output:

Error

Example 8:
str='it\'s a wonderful topic'

print(str)

Output:

it's a wonderful topic

Note: We can use value of one string variable into another.

Example:

name = 'John'

message = 'Hi {name}'

print(message)

Output:

Hi {name}

Concatenating Python strings

Concatenation of string means to join (or append) one string after another. For
concatenation of string we need to define two strings and use + operator.

Example:

msg1 = 'Good'

msg2 = ' Morning'

msg3=msg1+msg2

print(msg3)

Output:

Good Morning

String Functions

Count:

Return the number of times the value "apple" appears in the string.
Example:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("string")

print(n)

Output:

Find:

Searches the string for a specified value and returns the position of where it
was found

Example 1:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("string")

print(n)

Output:14 # string mentioned starts from

Example 2: txt="I am learning string functions. It's fun to learn about string"

n=[Link]("xyz")

print(n)

Output: -1 #as the string mentioned does not exist

Capitalize:

The capitalize() method returns a string where the first character is upper case,
and the rest is lower case.

Example:

txt="i am learning string functions. It's fun to learn about string"

n=[Link]()

print(n)

Output:

I am learning string functions. It's fun to learn about string


Title:

Converts the first character of each word to upper case

Example:

string functions. It's fun to learn about string"

n=[Link]()

print(n) txt="i am learning

Output:

I Am Learning String Functions. It'S Fun To Learn About String

Lower:

Converts a string into lower case

Example:

txt="I Am Learning String Functions. It'S Fun To Learn About String"

n=[Link]()

print(n)

Output:

i am learning string functions. it's fun to learn about string

upper:

Converts a string into upper case

Example:

txt="I Am Learning String Functions. It'S Fun To Learn About String"

n=[Link]()

print(n)

Output:

I AM LEARNING STRING FUNCTIONS. IT'S FUN TO LEARN ABOUT STRING

Swapcase:

Swaps cases, lower case becomes upper case and vice versa
Example:

txt="i AM LEARNING string FUNCTIONS. It'S fun TO LEARN ABOUT string"

n=[Link]()

print(n)

Output:

I am learning STRING functions. iT's FUN to learn about STRING

Replace:

Returns a string where a specified value is replaced with a specified value

Example:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("string","python")

print(n)

Output:

I am learning python functions. It's fun to learn about python

Join:

Converts the elements of an iterable into a string. In simpler words, it join all
items in a tuple into a string, using a hash character as separator

Example:

txt=("unit 1", "unit 2", "unit 3","unit 4")

n=".".join(txt)

print(n)

Output:

unit [Link] [Link] [Link] 4

isspace:

Returns True if all characters in the string are whitespaces.


The isspace() method returns True if all the characters in a string are
whitespaces, otherwise False.
Example 1:

txt=" "

n=[Link]()

print(n)

Output:

TURE

Example 2:

##txt="I am learning string functions. It's fun to learn about string"

txt=" "

n=[Link]()

print(n)

Output:

FALSE

Isdigit:

Returns True if all characters in the string are digits. The isdigit() method
returns True if all the characters are digits, otherwise False.

Example 1:

txt="12345"

n=[Link]()

print(n)

Output:

TRUE

Example 2:

txt="12345A"

n=[Link]()

print(n)

Output:
FALSE

isaplha()

Returns True if all characters in the string are alphabets. The isaplha() method
returns True if all the characters are alphabets, otherwise False.

Example:

str1="ThisIsGood"

print([Link]())

Output:

True

Slicing: will find substring from a string

Example:

a = ("a", "b", "c", "d", "e", "f", "g", "h")

x = slice(3, 5)

print(a[x])

Output:

('d', 'e')

Example 2:

s=’ HELLO ‘

print(s[3:6])

Output:

HEL

Split:

Splits the string at the specified separator, and returns a list. You can specify
the separator, default separator is white space.

Example:

txt="I am learning string functions. It's fun to learn about string"


n=[Link]()

print(n)

Output:

['I', 'am', 'learning', 'string', 'functions.', "It's", 'fun', 'to', 'learn', 'about', 'string']

Startswith:

Returns true if the string starts with the specified value.


The startswith() method returns True if the string starts with the specified
value, otherwise False.

Example 1:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("learning")

print(n)

Output:

False

Example 2:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("I")

print(n)

Output:

TRUE

Endwith()

Returns true if the string ends with the specified value

Example 1:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("string")

print(n)

Output:
TRUE

Example 2:

txt="I am learning string functions. It's fun to learn about string"

n=[Link]("str")

print(n)

Output:

FALSE

Common questions

Powered by AI

String slicing in Python is performed using a range of indices within square brackets, such as a[start:stop] to extract portions of a string. This operation is zero-indexed and includes characters up to, but not including, the stop index. For example, s='HELLO' uses s[3:6] to extract 'LO', which effectively retrieves a substring that might represent abbreviations or specific sections of formatted text . It's effective in situations requiring substrings, like parsing file paths or extracting protocol identifiers from URLs.

The .find() method searches for a specified value in a string and returns the position where it's found, or -1 if not found. For example, txt.find("string") on txt="I am learning string functions." returns 14 . The .count() method, on the other hand, counts the number of occurrences of a specified value. For example, txt.count("string") on the same txt returns 2, indicating "string" appears twice .

Triple quotes allow for multi-line strings and include line breaks and escape sequences as part of the string itself, preserving the exact format entered. This feature is useful for creating string literals or docstrings where text block formatting matters. For instance, using triple quotes, a string can span several lines, maintaining indentation and new lines which can be critical in structuring visible output or for documenting complex functions . However, while formatting can maintain textual layout, it also requires careful handling to avoid unwanted spacing or alignment issues, especially in code printing or logging.

The string .capitalize() method converts the first character of a string to uppercase and all other characters to lowercase. It's typically used when formatting sentences where the first letter needs emphasis . In contrast, .title() capitalizes the first letter of each word in a string. It's useful for formatting titles or headlines where each word should start with an uppercase letter. For example, using .title() on 'i am learning' results in 'I Am Learning', while .capitalize() would result in 'I am learning' .

The .isspace() method returns True only if all characters in a string are whitespace. Thus, even a single non-space character results in False. For example, a string containing only spaces (' ') returns True, but if there's an invisible non-space character or an embed character amongst them, such as a tab or newline (' \n'), the result is False . This method is useful to check if input strings are purely empty or only filled with space padding, vital for input validation in applications.

Concatenation in Python is achieved using the + operator, which merges multiple strings into one longer string, such as msg1='Good' + ' Morning' results in 'Good Morning' . While straightforward for small operations, excessive use of concatenation, especially within loops, may lead to inefficiency due to the creation of temporary strings for each operation. Instead, it's recommended to use methods like .join() for merging iterables, as it is more memory efficient and faster for large-scale or repeated operations, especially in data processing or logging tasks.

The .replace() method can be used for bulk updates or replacements within a string by substituting one substring with another throughout the entire string. For instance, txt.replace("string", "python") replaces every occurrence of "string" with "python" in a given text . It's useful for editing texts where multiple identical changes are needed. However, it cannot perform conditional replacements or differentiate context; it replaces all instances indiscriminately, which might not be desirable if specific instances need different treatment.

An error occurs when attempting to print a string like str1="This is a "important" String" because the quotes conflict. This can be rectified by either using different types of quotes, such as single quotes around the string (str1='This is a "important" String'), or escaping the internal quotes with a backslash (str1="This is a \"important\" String").

The .join() method helps in concatenating elements of an iterable into a single string with a given separator. It's used to efficiently merge list elements, as seen in joining tuples using separators like hashes or commas. A practical use is converting a list of sentence fragments into coherent sentences or merging CSV data for output. For example, join function in txt=("unit 1", "unit 2") with '.'.join(txt) outputs 'unit 1.unit 2', crucial in cases for format-specific exports or logs .

.startswith() and .endswith() methods are used to verify if a string begins or ends with a specified substring. .startswith() returns True if a string starts with the specified prefix; otherwise False. For example, 'I am learning'.startswith('I') returns True . .endswith() behaves similarly, checking the end of the string. In 'I am learning'.endswith('string'), it returns True since it ends with 'string' . Both methods serve essential roles in validating text patterns or protocols, such as ensuring URLs contain required schemas or files have expected extensions.

You might also like