Python Tutorial - 1 - String

How to Write String in Python

/*

  • File: string_learn.md
  • Project: 1_string
  • File Created: Friday, 3rd March 2023 12:18:41 pm
  • Author: Hanlin Gu (hg_fine_codes@163.com)

  • Last Modified: Saturday, 11th March 2023 3:48:30 pm
  • Modified By: Hanlin Gu (hg_fine_codes@163.com>)
    */

1. string

1.1. What is String in Python

To indicate string, one can use single quote ' or double quote " or triple quote """. Depending on what is in the string, if there is single or double quote in the string, it is recommended to use triple quote from the outside.

print('Hello World')

Output:

Hello World

To make print() shorter, one can define a variable like message to store the string information. And then print that variable instead print(message).

message = """Tom says it's "Bobby's World"!"""
print(message)

Output:

Tom says it's "Bobby's World"!

1.2. Length of String

To get the length of string is len().

message = 'Hello World'
print(len(message))

Output

11

1.3. Slicing of String

Partition of string is to write the variable followed by brackets with numbers inside var_name[].

In python, the number counting starts from 0. One specific number [n] means to get that letter at the specific position n+1.

[-n] means counting from the end, for example [-1] is the last letter.

[start:stop] means the string that starts from start to the stop, but include the [start] and exclude the [stop].

[:stop] gives the letters from the beginning to the stop which is equivalent to [0:stop].

Similarly, [start:] means all the letters from the start to the last letter of the string.

message = 'Hello World'
print(message[0])
print(message[-2])
print(message[0:5])
print(message[:5])
print(message[6:])

Output

H
l
Hello
Hello
World

1.4. String Methods

The use of different methods, return a new string with the methods applied.

  • all lower case: var_name.lower()

  • all upper case: var_name.upper()

  • count certain number of characters: var_name.count()

count() takes a string as an argument.

  • find certain index: var_name.find()

found() also takes a string argument, and returns where that string first appears. If a string is not find, then it will return -1.

message = 'Hello World'
print(message.lower())
print(message.upper())
print(message.count('Hello'))
print(message.count('l'))
print(message.find('World'))
print(message.find('abc'))

Output:

hello world
HELLO WORLD
1
3
6
-1
  • replace some characters by other characters: var_name.replace(var1,var2)

.replace(var1,var2) takes two variables, the first variable var1 is the string that one wants to be replaced and the second variable var2 is the string to replace the original string.

message = 'Hello World'
new_message = message.replace('World','Universe')
print(message)
print(new_message)

Output:

Hello World
Hello Universe

If one set the replaced string as the old string, then the old string will be changed.

message = 'Hello World'
message = message.replace('World','Universe')
print(message)

Output:

Hello Universe
  • Add multiple strings and concatenate them together

(1) Use + to connect two strings

greeting = 'Hello'
name = 'Michael'

message = greeting + name

print(message)

Output:

HelloMichael

However, there is no space between the two strings and it’s very easy to make mistakes like this during concatenation.

greeting = 'Hello'
name = 'Michael'

message = greeting + ', ' + name

print(message)

Output:

Hello, Michael

(2) formatted string .format() method

But, if the sentience is long, it’s hard to keep track of the variables to write in this way.

greeting = 'Hello'
name = 'Michael'

message = greeting + ', ' + name + '. Welcome!'

print(message)

Output:

Hello, Michael. Welcome!

To write the sentence above, one would use method .format() by leaving the placeholder {} in the string to take the places of the variables and add the variable names in the brackets of format() in orders.

greeting = 'Hello'
name = 'Michael'

message = '{}, {}. Welcome!'.format(greeting, name)

print(message)

Output:

Hello, Michael. Welcome!

This is easier to read.

(3) f strings: for Python 3.6 and above

This f string method is very convenient to use since it can also combine other methods. In the .format() method, this also works.

greeting = 'Hello'
name = 'Michael'

message1 = f'{greeting}, {name}. Welcome!'
message2 = f'{greeting}, {name.upper()}. Welcome!'

print(message1)
print(message2)

Output:

Hello, Michael. Welcome!
Hello, MICHAEL. Welcome!
  • all methods available for the variable: dir(vir_name)
greeting = 'Hello'
name = 'Michael'

print(dir(name))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
  • How does the String Methods Work help(obj_type)
print(help(str))

For certain method, help(obj_type.method_name)

print(help(str.rsplit))

Output:

rsplit(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.
    
      sep
        The delimiter according which to split the string.
        None (the default value) means split according to any whitespace,
        and discard empty strings from the result.
      maxsplit
        Maximum number of splits to do.
        -1 (the default value) means no limit.
    
    Splits are done starting at the end of the string and working to the front.

None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值