简体   繁体   中英

Printing a specific chosen line of a string ; Python3

Ok so, let's say I have a string that looks something like this.

str = """
     abcedjhg
     by234aaD
     Xucu2345
     Cmn23481         
     vj3h4123
     """

I would like to be able to select a single line from that string and print it out

Usage eg

>> input("What line would you like to view? \n : ")
>> What line would you like to view? 
>>  : 3
>> Xucu2345

Im not too sure how to actually select the line and store it as a str for it to be printed.

I'd appreciate your help! As usual, if you would like me to explain it better just ask. I'm not sure what exactly to ask w/ a question like this :)

Use split to split str and print the desired string

list=str.split("\n")
print(list[3].strip())

strip will truncate the leading and succeeding white spaces

I suggest you using str.split("\\n") method to build a list including each line of the string, and also str.strip() to remove the leading whitespaces.
And please do not use the str as the variable name, because it is also the name of string type in Python. It could lead to mistakes.
Here is my solution:

s  = """
     abcedjhg
     by234aaD
     Xucu2345
     Cmn23481         
     vj3h4123
     """

lines = [line.strip() for line in s.split("\n")]
line_nb = input("What line would you like to view? \n : ")

print(lines[int(line_nb)])

# What line would you like to view? 
# : 3
#Xucu2345

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM