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

String

The document provides an overview of string manipulation in Python, covering topics such as string creation, multiline strings, string indexing, and various string methods including upper(), lower(), strip(), replace(), split(), and format(). It explains how to check for substring presence, slice strings, and use string formatting with placeholders. Additionally, it discusses methods for counting occurrences, checking string endings, and finding values within strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

String

The document provides an overview of string manipulation in Python, covering topics such as string creation, multiline strings, string indexing, and various string methods including upper(), lower(), strip(), replace(), split(), and format(). It explains how to check for substring presence, slice strings, and use string formatting with placeholders. Additionally, it discusses methods for counting occurrences, checking string endings, and finding values within strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Strings Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

In [ ]: print("Hello")
print('Hello')

Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Example

In [1]:
a = "Hello"
print(a)

Hello

Multiline Strings You can assign a multiline string to a variable by using three quotes:

Example You can use three double quotes:

In [2]: a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Or three single quotes:

Example

In [3]:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example Get the character at position 1 (remember that the first character has the position 0):

In [4]:
a = "Hello, World!"
print(a[1])

Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example Loop through the letters in the word "banana":

In [5]:
for x in "banana":
print(x)

b
a
n
a
n
a

String Length To get the length of a string, use the len() function.

Example The len() function returns the length of a string:

In [6]:
a = "Hello, World!"
print(len(a))
13

Check String To check if a certain phrase or character is present in a string, we can use the keyword in.

Example Check if "free" is present in the following text:

In [7]: txt = "The best things in life are free!"


print("free" in txt)

True

Use it in an if statement:

Example Print only if "free" is present:

In [8]:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Yes, 'free' is present.

Check if NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Example Check if "expensive" is NOT present in the following text:

In [9]:
txt = "The best things in life are free!"
print("expensive" not in txt)

True

Use it in an if statement:

Example print only if "expensive" is NOT present:

In [10]:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

No, 'expensive' is NOT present.

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

Specify the start index and the end index, separated by a colon, to return a part of the string.

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

In [11]: b = "Hello, World!"


print(b[2:5])

llo

Note: The first character has index 0.

Slice From the Start By leaving out the start index, the range will start at the first character:

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

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

Hello

Slice To the End By leaving out the end index, the range will go to the end:

Example Get the characters from position 2, and all the way to the end:

In [13]:
b = "Hello, World!"
print(b[2:])

llo, World!

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):

In [14]:
b = "Hello, World!"
print(b[-5:-2])
orl

Upper Case Example The upper() method returns the string in upper case:

In [15]:
a = "Hello, World!"
print(a.upper())

HELLO, WORLD!

Lower Case Example The lower() method returns the string in lower case:

In [16]:
a = "Hello, World!"
print(a.lower())

hello, world!

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:

In [17]:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Hello, World!

Replace String Example The replace() method replaces a string with another string:

In [18]:
a = "Hello, World!"
print(a.replace("H", "J"))

Jello, World!

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

Example The split() method splits the string into substrings if it finds instances of the separator:

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

['Hello', ' World!']

Python String capitalize() Method

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

Example Upper case the first letter in this sentence:

In [20]:
txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

Hello, and welcome to my world.

In [21]:
txt = "python is FUN!"

x = txt.capitalize()

print (x)

Python is fun!

Example See what happens if the first character is a number:

In [22]:
txt = "36 is MY age."

x = txt.capitalize()

print (x)

36 is my age.

String casefold() Method

The casefold() method returns a string where all the characters are lower case.

Example Make the string lower case:


In [23]:
txt = "Hello, And Welcome To My World!"

x = txt.casefold()

print(x)

hello, and welcome to my world!

String center() Method

The center() method will center align the string, using a specified character (space is default) as the fill character.

Syntax string.center(length, character)

length Required: The length of the returned string character Optional: The character to fill the missing space on each side. Default is " " (space)

Example Print the word "banana", taking up the space of 20 characters, with "banana" in the middle:

In [24]:
txt = "banana"

x = txt.center(20)

print(x)

banana

Example Using the letter "O" as the padding character:

In [25]: txt = "banana"

x = txt.center(20, "O")

print(x)

OOOOOOObananaOOOOOOO

String count() Method

The count() method returns the number of times a specified value appears in the string.

Syntax string.count(value, start, end)

Parameter Values Parameter Description value Required : A String. The string to value to search for start Optional : An Integer. The position to start the
search. Default is 0 end Optional : An Integer. The position to end the search. Default is the end of the string

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

In [26]: txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

Example Search from position 10 to 24:

In [29]:
txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple", 10, 24)

print(x)

String endswith() Method

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

Syntax string.endswith(value, start, end)

Parameter Values Parameter Description value Required: The value to check if the string ends with. This value parameter can also be a tuple, then the
method returns true if the string ends with any of the tuple values. start Optional: An Integer specifying at which position to start the search end
Optional: An Integer specifying at which position to end the search

Example Check if the string ends with a punctuation sign (.):

In [30]:
txt = "Hello, welcome to my world."

x = txt.endswith(".")
print(x)

True

String find() Method

The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

Syntax string.find(value, start, end)

Parameter Values value Required: The value to search for start Optional: Where to start the search. Default is 0 end Optional: Where to end the search.
Default is to the end of the string

Example Where in the text is the word "welcome"?:

In [31]:
txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)

Example Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:

In [32]:
txt = "Hello, welcome to my world."

x = txt.find("e", 5, 10)

print(x)

Example If the value is not found, the find() method returns -1, but the index() method will raise an exception:

In [33]: txt = "Hello, welcome to my world."

print(txt.find("q"))
print(txt.index("q"))

-1

---------------------------------------------------------------------------ValueError Traceback (most recent call las


1 txt = "Hello, welcome to my world."
3 print(txt.find("q"))
----> 4 print(txt.index("q"))
ValueError: substring not found

String format() Method

The format() method formats the specified value(s) and insert them inside the string's placeholder.

The format() method returns the formatted string.

Syntax string.format(value1, value2...)

Parameter Values

value1, value2... Required: One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The values can be of any data type.

Example Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:

In [34]:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

For only 49.00 dollars!

The Placeholders The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.

Example Using different placeholder values:

In [36]: txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36

Formatting Types

Inside the placeholders you can add a formatting type to format the result:

:< :Left aligns the result (within the available space)

#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.

In [37]:
txt = "We have {:<8} chickens."
print(txt.format(49))

We have 49 chickens.

:> :Right aligns the result (within the available space)

#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.

In [38]:
txt = "We have {:>8} chickens."
print(txt.format(49))

We have 49 chickens.

:^ :Center aligns the result (within the available space)

In [39]:
txt = "We have {:^8} chickens."
print(txt.format(49))

We have 49 chickens.

:= :Places the sign to the left most position

In [40]:
txt = "The temperature is {:=8} degrees celsius."

print(txt.format(-5))

The temperature is - 5 degrees celsius.

:+ :Use a plus sign to indicate if the result is positive or negative

In [43]:
txt = "The temperature is between {:+} and {:+} degrees celsius."

print(txt.format(-3, 7))

The temperature is between -3 and +7 degrees celsius.

:- :Use a minus sign for negative values only

In [44]:
txt = "The temperature is between {:-} and {:-} degrees celsius."

print(txt.format(-3, 7))

The temperature is between -3 and 7 degrees celsius.

:- :Use a minus sign for negative values only

In [45]:
txt = "The temperature is between {:-} and {:-} degrees celsius."

print(txt.format(-3, 7))

The temperature is between -3 and 7 degrees celsius.

: :Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)

In [46]: txt = "The temperature is between {: } and {: } degrees celsius."

print(txt.format(-3, 7))

The temperature is between -3 and 7 degrees celsius.

:, :Use a comma as a thousand separator


In [47]:
txt = "The universe is {:,} years old."

print(txt.format(13800000000))

The universe is 13,800,000,000 years old.

:_ Use a underscore as a thousand separator

In [48]: txt = "The universe is {:_} years old."

print(txt.format(13800000000))

The universe is 13_800_000_000 years old.

:b Binary format

In [49]:
txt = "The binary version of {0} is {0:b}"

print(txt.format(5))

The binary version of 5 is 101

:d Decimal format

In [50]: txt = "We have {:d} chickens."


print(txt.format(0b101))

We have 5 chickens.

:f Fix point number format

#Use "f" to convert a number into a fixed point number, default with 6 decimals, but use a period followed by a number to specify the number of
decimals:

In [51]: txt = "The price is {:.2f} dollars."


print(txt.format(45))

The price is 45.00 dollars.

#without the ".2" inside the placeholder, this number will be displayed like this:

In [52]: txt = "The price is {:f} dollars."


print(txt.format(45))

The price is 45.000000 dollars.

:o Octal format

In [53]: txt = "The octal version of {0} is {0:o}"

print(txt.format(10))

The octal version of 10 is 12

:% Percentage format

In [54]:
txt = "You scored {:%}"
print(txt.format(0.25))

You scored 25.000000%

In [55]:
txt = "You scored {:.0%}"
print(txt.format(0.25))

You scored 25%

String index() Method

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

The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

Syntax string.index(value, start, end)


Parameter Description value: Required. The value to search for start: Optional. Where to start the search. Default is 0 end: Optional. Where to end the
search. Default is to the end of the string

Example Where in the text is the word "welcome"?:

In [56]:
txt = "Hello, welcome to my world."

x = txt.index("welcome")

print(x)

Example Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:

In [57]:
txt = "Hello, welcome to my world."

x = txt.index("e", 5, 10)

print(x)

The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found.

In [58]: txt = "Hello, welcome to my world."

print(txt.find("q"))
print(txt.index("q"))

-1

---------------------------------------------------------------------------ValueError Traceback (most recent call las


1 txt = "Hello, welcome to my world."
3 print(txt.find("q"))
----> 4 print(txt.index("q"))
ValueError: substring not found

String isalnum() Method

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

Example of characters that are not alphanumeric: (space)!#%&? etc.

Syntax string.isalnum()

In [59]:
txt = "Company12"

x = txt.isalnum()

print(x)

True

In [60]: txt = "Company 12"

x = txt.isalnum()

print(x)

False

String isalpha() Method

The isalpha() method returns True if all the characters are alphabet letters (a-z).

Example of characters that are not alphabet letters: numbers,(space)!#%&? etc.

Syntax string.isalpha()

In [61]: txt = "CompanyX"

x = txt.isalpha()

print(x)

True

In [62]:
txt = "Company10"

x = txt.isalpha()
print(x)

False

String isascii() Method

The isascii() method returns True if all the characters are ascii characters (a-z).

In [63]:
txt = "Company123"

x = txt.isascii()

print(x)

True

String isdecimal() Method

The isdecimal() method returns True if all the characters are decimals (0-9).

In [64]:
txt = "1234"

x = txt.isdecimal()

print(x)

True

String isdigit() Method

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

Exponents, like ², are also considered to be a digit.

Syntax string.isdigit()

In [67]:
txt = "581926"

x = txt.isdigit()

print(x)

True

string isidentifier() Method

The isidentifier() method returns True if the string is a valid identifier, otherwise False.

A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a
number, or contain any spaces.

Syntax string.isidentifier()

In [69]:
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"

print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())

True
True
False
False

String islower() Method

The islower() method returns True if all the characters are in lower case, otherwise False.

Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax string.islower()

In [1]:
txt = "hello world!"

x = txt.islower()

print(x)
True

In [2]:
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"

print(a.islower())
print(b.islower())
print(c.islower())

False
True
False

String isnumeric() Method

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.

Exponents, like ² and ¾ are also considered to be numeric values.

"-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.

Syntax string.isnumeric()

In [4]:
a = "565543"
b = "-1"
c = "1.5"

x = a.isnumeric()
y = b.isnumeric()
z = c.isnumeric()

print(x)
print(y)
print(z)

True
False
False

String isspace() Method

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

Syntax string.isspace()

In [5]:
txt = " "

x = txt.isspace()

print(x)

True

In [6]:
txt = " s "

x = txt.isspace()

print(x)

False

String istitle() Method

The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.

Symbols and numbers are ignored.

Syntax string.istitle()

In [7]: txt = "Hello, And Welcome To My World!"

x = txt.istitle()

print(x)

True

In [8]: a = "HELLO, AND WELCOME TO MY WORLD"


b = "Hello"
c = "22 Names"
d = "This Is %'!?"

print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())

False
True
True
True

String isupper() Method

The isupper() method returns True if all the characters are in upper case, otherwise False.

Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax string.isupper()

In [9]:
txt = "THIS IS NOW!"

x = txt.isupper()

print(x)

True

In [10]:
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"

print(a.isupper())
print(b.isupper())
print(c.isupper())

False
False
True

String join() Method

The join() method takes all items in an iterable and joins them into one string.

A string must be specified as the separator.

Syntax string.join(iterable)

Parameter Values iterable: Required. Any iterable object where all the returned values are strings

Note: When using a dictionary as an iterable, the returned values are the keys, not the values.

In [11]:
myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

John#Peter#Vicky

In [12]:
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"

x = mySeparator.join(myDict)

print(x)

nameTESTcountry

String ljust() Method

The ljust() method will left align the string, using a specified character (space is default) as the fill character.

Syntax string.ljust(length, character)

Parameter Description length: Required. The length of the returned string character: Optional. A character to fill the missing space (to the right of the
string). Default is " " (space).

Example Return a 20 characters long, left justified version of the word "banana":

In [13]:
txt = "banana"

x = txt.ljust(20)

print(x, "is my favorite fruit.")

banana is my favorite fruit.


Note: In the result, there are actually 14 whitespaces to the right of the word banana.

Example Using the letter "O" as the padding character:

In [14]: txt = "banana"

x = txt.ljust(20, "O")

print(x)

bananaOOOOOOOOOOOOOO

String lower() Method

The lower() method returns a string where all characters are lower case.

Symbols and Numbers are ignored.

Syntax string.lower()

In [ ]: Example
Lower case the string:

In [15]:
txt = "Hello my FRIENDS"

x = txt.lower()

print(x)

hello my friends

String lstrip() Method

The lstrip() method removes any leading characters (space is the default leading character to remove)

Syntax string.lstrip(characters)

Example Remove spaces to the left of the string:

In [16]:
txt = " banana "

x = txt.lstrip()

print("of all fruits", x, "is my favorite")

of all fruits banana is my favorite

Example Remove the leading characters:

In [17]:
txt = ",,,,,ssaaww.....banana"

x = txt.lstrip(",.asw")

print(x)

banana

String partition() Method

The partition() method searches for a specified string, and splits the string into a tuple containing three elements.

The first element contains the part before the specified string.

The second element contains the specified string.

The third element contains the part after the string.

Note: This method searches for the first occurrence of the specified string.

Syntax string.partition(value)

Parameter Description value Required. The string to search for

ExampleGet your own Python Server Search for the word "bananas", and return a tuple with three elements:

1 - everything before the "match" 2 - the "match" 3 - everything after the "match"

In [18]:
txt = "I could eat bananas all day"

x = txt.partition("bananas")
print(x)

('I could eat ', 'bananas', ' all day')

Example If the specified value is not found, the partition() method returns a tuple containing: 1 - the whole string, 2 - an empty string, 3 - an empty
string:

In [19]: txt = "I could eat bananas all day"

x = txt.partition("apples")

print(x)

('I could eat bananas all day', '', '')

String rstrip() Method

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

Syntax string.rstrip(characters)

Parameter Description characters: Optional. A set of characters to remove as trailing characters

Example Remove any white spaces at the end of the string:

In [20]:
txt = " banana "

x = txt.rstrip()

print("of all fruits", x, "is my favorite")

of all fruits banana is my favorite

Example Remove the trailing characters if they are commas, periods, s, q, or w:

In [21]:
txt = "banana,,,,,ssqqqww....."

x = txt.rstrip(",.qsw")

print(x)

banana

String split() Method

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax string.split(separator, maxsplit)

Parameter Description separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator maxsplit
Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"

In [ ]:
Example
Split a string into a list where each word is a list item:

In [22]:
txt = "welcome to the jungle"

x = txt.split()

print(x)

['welcome', 'to', 'the', 'jungle']

Example Split the string, using comma, followed by a space, as a separator:

In [25]:
txt = "hello, my name is Peter, I am 26 years old"

x = txt.split(" ,")

print(x)

['hello, my name is Peter, I am 26 years old']

Example Use a hash character as a separator:


In [26]:
txt = "apple#banana#cherry#orange"

x = txt.split("#")

print(x)

['apple', 'banana', 'cherry', 'orange']

Example Split the string into a list with max 2 items:

In [27]:
txt = "apple#banana#cherry#orange"

# setting the maxsplit parameter to 1, will return a list with 2 elements!


x = txt.split("#", 1)

print(x)

['apple', 'banana#cherry#orange']

String splitlines() Method

The splitlines() method splits a string into a list. The splitting is done at line breaks.

Syntax string.splitlines(keeplinebreaks)

Parameter Description keeplinebreaks Optional. Specifies if the line breaks should be included (True), or not (False). Default value is False

Example Split a string into a list where each line is a list item:

In [28]:
txt = "Thank you for the music\nWelcome to the jungle"

x = txt.splitlines()

print(x)

['Thank you for the music', 'Welcome to the jungle']

Example Split the string, but keep the line breaks:

In [29]:
txt = "Thank you for the music\nWelcome to the jungle"

x = txt.splitlines(True)

print(x)

['Thank you for the music\n', 'Welcome to the jungle']

String startswith() Method

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

Syntax string.startswith(value, start, end)

Parameter Description value Required. The value to check if the string starts with. This value parameter can also be a tuple, then the method returns
true if the string starts with any of the tuple values. start Optional. An Integer specifying at which position to start the search end Optional. An Integer
specifying at which position to end the search

Example Check if the string starts with "Hello":

In [30]:
txt = "Hello, welcome to my world."

x = txt.startswith("Hello")

print(x)

True

Example Check if position 7 to 20 starts with the characters "wel":

In [31]:
txt = "Hello, welcome to my world."

x = txt.startswith("wel", 7, 20)

print(x)

True

String strip() Method


The strip() method removes any leading, and trailing whitespaces.

Leading means at the beginning of the string, trailing means at the end.

You can specify which character(s) to remove, if not, any whitespaces will be removed.

Syntax string.strip(characters)

Parameter Description characters Optional. A set of characters to remove as leading/trailing characters

Example Remove spaces at the beginning and at the end of the string:

In [32]: txt = " banana "

x = txt.strip()

print("of all fruits", x, "is my favorite")

of all fruits banana is my favorite

Example Remove the leading and trailing characters:

In [33]: txt = ",,,,,rrttgg.....banana....rrr"

x = txt.strip(",.grt")

print(x)

banana

String swapcase() Method

The swapcase() method returns a string where all the upper case letters are lower case and vice versa.

Syntax string.swapcase()

Example Make the lower case letters upper case and the upper case letters lower case:

In [34]:
txt = "Hello My Name Is PETER"

x = txt.swapcase()

print(x)

hELLO mY nAME iS peter

String title() Method

The title() method returns a string where the first character in every word is upper case. Like a header, or a title.

If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Syntax string.title()

Example Make the first letter in each word upper case:

In [35]:
txt = "Welcome to my world"

x = txt.title()

print(x)

Welcome To My World

Example Make the first letter in each word upper case:

In [36]: txt = "Welcome to my 2nd world"

x = txt.title()

print(x)

Welcome To My 2Nd World

Example Note that the first letter after a non-alphabet letter is converted into a upper case letter:

In [37]: txt = "hello b2b2b2 and 3g3g3g"

x = txt.title()
print(x)

Hello B2B2B2 And 3G3G3G

String upper() Method

The upper() method returns a string where all characters are in upper case.

Symbols and Numbers are ignored.

Syntax string.upper()

In [38]: txt = "Hello my friends"

x = txt.upper()

print(x)

HELLO MY FRIENDS

String zfill() Method

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.

If the value of the len parameter is less than the length of the string, no filling is done.

Syntax string.zfill(len)

Parameter Description len Required. A number specifying the desired length of the string

Example Fill the string with zeros until it is 10 characters long:

In [39]:
txt = "50"

x = txt.zfill(10)

print(x)

0000000050

Example Fill the strings with zeros until they are 10 characters long:

In [40]:
a = "hello"
b = "welcome to the jungle"
c = "10.000"

print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))

00000hello
welcome to the jungle
000010.000

You might also like