Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22852

IslandT: Python Tutorial — Chapter 4

$
0
0

In this tutorial, I am going to show you how to work with strings in Python!

How to represent a string

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

aname = ‘Jimmy’
anothername = “James”

How to combine two strings

When you combined two strings with +, you will get a new string in return…

a = “Hello ” + “World” # Hello World

How to count how many times a word appears within a string

In order to count the number of times a word or words appear within a string you can use the string count method, for example,

marry = "has a little lamb, little lamb"
print(marry.count("little lamb")) # 2

How to find the position of a word within a string

In order to find the position of a word, you will use the find method of a string.

y = "I love you all, I really love you all!"
x = y.find("love") # 2, after this method finds the word it will stop and will not continue to look for the second one.

How to check whether a string contains all numbers

isnumber = "23456".isnumeric() # return true because this string contains all numbers

How to convert a string into lower case

lowercase = "HelLo".lower() # hello

How to convert the first character in the string to a capital letter

lowercase = "gelLo".capitalize() # Gello

How to find the index value of a character within a string

lowercase = "gelLo".index('l') #2, the index count starts from index 0

How to replace a word within a string

hi = "I like you"

y = hi.replace("you", "myself") # I like myself

How to add a string of numbers to a number

You will need to convert that string into a number first then add them both up!

num = int("123") + 6 # 129

There are still a lot of methods that I have not been able to cover but you can read them on the official website of Python under the python document sections.


Viewing all articles
Browse latest Browse all 22852

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>