Skip to content

Python Journey

My Coding Blog

Menu
  • Links
Menu

Python>>String Methods

Posted on August 29, 2022August 29, 2022 by coden00b

Here are some common String Methods or Attributes that you can use in modifying strings.

Assuming x is the string:

a. x.upper()  – converts to upper case

> x = ‘Free Linux Tutorials’
>>> x.upper()
‘FREE LINUX TUTORIALS’
>>> print(x)
Free Linux Tutorials
>>> y = x.upper()
>>> print (y)
FREE LINUX TUTORIALS

 

b.  x.lower() = converts to lower case

> print(x)
Free Linux Tutorials
>>> x.lower()
‘free linux tutorials’
>>> y = x.lower()
>>> print(y)
free linux tutorials

 

c. x.split() = to split strings

> print(x)
Free Linux Tutorials
>>> x.split()
[‘Free’, ‘Linux’, ‘Tutorials’]

> x.split(‘r’)
[‘F’, ‘ee Linux Tuto’, ‘ials’]

 

d.  len(x) = to get the length of strings or number of characters

> print(x)
Free Linux Tutorials
>>> len(x)
20

 

e. x.count() = count the number of times that the character/words appear in the string

x = ‘This These That Those’
>>> x.count(‘t’)
1
>>> x.count(‘T’)
4

>> x = ‘I love apples. We love apples. They love apples.’
>>> x.count(‘apples’)
3

 

f. x.find() = to find character(s) in the string

>> print (x)
I love apples. We love apples. They love apples.
>>> x.find(‘apples’)
7

where 7 is the 7th position (from previous lesson, it always start with 0)

>> x.find(‘We’)
15
>>> x.find(‘They love’)
31

 

x.find(‘apples’,7)
7

begin searching on 7th position (1st word apple is on 7th position)

>> x.find(‘apples’,8)
23

begin searching on 8th position (1st word apple is excluded since it is on 7th position, so it starts counting on 8th)

 

g.  .replace() = to replace characters(s)

> print(x)
I love apples. We love apples. They love apples.
>>> x.replace(‘apples’,’oranges’)
‘I love oranges. We love oranges. They love oranges.’

>> x.replace(‘I’,’We’)
‘We love apples. We love apples. They love apples.’

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • The Zen of Python
  • Python>>String Interpolation and Formatting
  • Python>>String Methods
  • Python>>String Concatenation
  • Python>>Strings: Indexing and Slicing

Recent Comments

No comments to show.

Archives

  • January 2023
  • August 2022

Categories

  • Blog
  • Data Types